Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6d856b93e | ||
|
|
ef843d400e | ||
|
|
654ca0da91 | ||
|
|
aa66e08034 | ||
|
|
268d4f7cf8 | ||
|
|
0de5742b04 | ||
|
|
321251907a | ||
|
|
d5c86c9af6 | ||
|
|
b500a36a94 | ||
|
|
a75a9b427f | ||
|
|
1310045629 | ||
|
|
579a69eb77 | ||
|
|
9ee8c4f543 | ||
|
|
55560f5116 | ||
|
|
f98679d217 | ||
|
|
3710ddb611 | ||
|
|
3fce14bbcf | ||
|
|
d430a0624b |
No files matched your search
@@ -308,11 +308,31 @@ 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
|
||||
@@ -349,8 +369,8 @@ jobs:
|
||||
exit 0
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
git config user.name "${{ steps.app_bot.outputs.name }}"
|
||||
git config user.email "${{ steps.app_bot.outputs.email }}"
|
||||
|
||||
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,3 +17,4 @@ release/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
@@ -22,7 +22,7 @@
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.76",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
|
||||
@@ -62,6 +62,7 @@ function makeSnapshot(input: {
|
||||
messages: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
|
||||
@@ -37,6 +37,8 @@ function createSendTurnHarness() {
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
},
|
||||
collabReceiverTurns: new Map(),
|
||||
collabReceiverItems: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -75,6 +77,8 @@ function createThreadControlHarness() {
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
collabReceiverTurns: new Map(),
|
||||
collabReceiverItems: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -117,6 +121,8 @@ function createPendingUserInputHarness() {
|
||||
},
|
||||
],
|
||||
]),
|
||||
collabReceiverTurns: new Map(),
|
||||
collabReceiverItems: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -135,6 +141,44 @@ function createPendingUserInputHarness() {
|
||||
return { manager, context, requireSession, writeMessage, emitEvent };
|
||||
}
|
||||
|
||||
function createCollabNotificationHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
provider: "codex",
|
||||
status: "running",
|
||||
threadId: asThreadId("thread_1"),
|
||||
runtimeMode: "full-access",
|
||||
model: "gpt-5.3-codex",
|
||||
activeTurnId: "turn_parent",
|
||||
resumeCursor: { threadId: "provider_parent" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
account: {
|
||||
type: "unknown",
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
},
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
collabReceiverTurns: new Map<string, string>(),
|
||||
collabReceiverItems: new Map<string, string>(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
|
||||
const emitEvent = vi
|
||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
||||
.mockImplementation(() => {});
|
||||
const updateSession = vi
|
||||
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
return { manager, context, emitEvent, updateSession };
|
||||
}
|
||||
|
||||
describe("classifyCodexStderrLine", () => {
|
||||
it("ignores empty lines", () => {
|
||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||
@@ -721,6 +765,8 @@ describe("respondToUserInput", () => {
|
||||
},
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
collabReceiverTurns: new Map(),
|
||||
collabReceiverItems: new Map(),
|
||||
};
|
||||
type ApprovalRequestContext = {
|
||||
session: typeof context.session;
|
||||
@@ -748,6 +794,197 @@ describe("respondToUserInput", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("collab child conversation routing", () => {
|
||||
it("rewrites child notification turn ids onto the parent turn", () => {
|
||||
const { manager, context, emitEvent } = createCollabNotificationHarness();
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||
}
|
||||
).handleServerNotification(context, {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: {
|
||||
type: "collabAgentToolCall",
|
||||
id: "call_collab_1",
|
||||
receiverThreadIds: ["child_provider_1"],
|
||||
},
|
||||
threadId: "provider_parent",
|
||||
turnId: "turn_parent",
|
||||
},
|
||||
});
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||
}
|
||||
).handleServerNotification(context, {
|
||||
method: "item/agentMessage/delta",
|
||||
params: {
|
||||
threadId: "child_provider_1",
|
||||
turnId: "turn_child_1",
|
||||
itemId: "msg_child_1",
|
||||
delta: "working",
|
||||
},
|
||||
});
|
||||
|
||||
expect(emitEvent).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({
|
||||
method: "item/agentMessage/delta",
|
||||
turnId: "turn_parent",
|
||||
itemId: "msg_child_1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
|
||||
const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||
}
|
||||
).handleServerNotification(context, {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: {
|
||||
type: "collabAgentToolCall",
|
||||
id: "call_collab_1",
|
||||
receiverThreadIds: ["child_provider_1"],
|
||||
},
|
||||
threadId: "provider_parent",
|
||||
turnId: "turn_parent",
|
||||
},
|
||||
});
|
||||
emitEvent.mockClear();
|
||||
updateSession.mockClear();
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||
}
|
||||
).handleServerNotification(context, {
|
||||
method: "turn/started",
|
||||
params: {
|
||||
threadId: "child_provider_1",
|
||||
turn: { id: "turn_child_1" },
|
||||
},
|
||||
});
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||
}
|
||||
).handleServerNotification(context, {
|
||||
method: "turn/completed",
|
||||
params: {
|
||||
threadId: "child_provider_1",
|
||||
turn: { id: "turn_child_1", status: "completed" },
|
||||
},
|
||||
});
|
||||
|
||||
expect(emitEvent).not.toHaveBeenCalled();
|
||||
expect(updateSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rewrites child approval requests onto the parent turn", () => {
|
||||
const { manager, context, emitEvent } = createCollabNotificationHarness();
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||
}
|
||||
).handleServerNotification(context, {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: {
|
||||
type: "collabAgentToolCall",
|
||||
id: "call_collab_1",
|
||||
receiverThreadIds: ["child_provider_1"],
|
||||
},
|
||||
threadId: "provider_parent",
|
||||
turnId: "turn_parent",
|
||||
},
|
||||
});
|
||||
emitEvent.mockClear();
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
|
||||
}
|
||||
).handleServerRequest(context, {
|
||||
id: 42,
|
||||
method: "item/commandExecution/requestApproval",
|
||||
params: {
|
||||
threadId: "child_provider_1",
|
||||
turnId: "turn_child_1",
|
||||
itemId: "call_child_1",
|
||||
command: "bun install",
|
||||
},
|
||||
});
|
||||
|
||||
expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
turnId: "turn_parent",
|
||||
itemId: "call_child_1",
|
||||
}),
|
||||
);
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: "item/commandExecution/requestApproval",
|
||||
turnId: "turn_parent",
|
||||
itemId: "call_child_1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rewrites child task notifications onto the parent collab item when no child item id exists", () => {
|
||||
const { manager, context, emitEvent } = createCollabNotificationHarness();
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||
}
|
||||
).handleServerNotification(context, {
|
||||
method: "item/completed",
|
||||
params: {
|
||||
item: {
|
||||
type: "collabAgentToolCall",
|
||||
id: "call_collab_1",
|
||||
receiverThreadIds: ["child_provider_1"],
|
||||
},
|
||||
threadId: "provider_parent",
|
||||
turnId: "turn_parent",
|
||||
},
|
||||
});
|
||||
emitEvent.mockClear();
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||
}
|
||||
).handleServerNotification(context, {
|
||||
method: "codex/event/task_started",
|
||||
params: {
|
||||
threadId: "child_provider_1",
|
||||
msg: {
|
||||
type: "task_started",
|
||||
turn_id: "turn_child_1",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: "codex/event/task_started",
|
||||
turnId: "turn_parent",
|
||||
itemId: "call_collab_1",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
|
||||
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
|
||||
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
|
||||
|
||||
@@ -70,6 +70,8 @@ interface CodexSessionContext {
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
|
||||
collabReceiverTurns: Map<string, TurnId>;
|
||||
collabReceiverItems: Map<string, ProviderItemId>;
|
||||
nextRequestId: number;
|
||||
stopping: boolean;
|
||||
}
|
||||
@@ -571,6 +573,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
collabReceiverTurns: new Map(),
|
||||
collabReceiverItems: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
@@ -732,6 +736,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
const context = this.requireSession(input.threadId);
|
||||
context.collabReceiverTurns.clear();
|
||||
context.collabReceiverItems.clear();
|
||||
|
||||
const turnInput: Array<
|
||||
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
||||
@@ -1121,7 +1127,18 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
context: CodexSessionContext,
|
||||
notification: JsonRpcNotification,
|
||||
): void {
|
||||
const route = this.readRouteFields(notification.params);
|
||||
const rawRoute = this.readRouteFields(notification.params);
|
||||
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
|
||||
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
|
||||
const childParentItemId = this.readChildParentItemId(context, notification.params);
|
||||
const isChildConversation = childParentTurnId !== undefined;
|
||||
const effectiveItemId = rawRoute.itemId ?? childParentItemId;
|
||||
if (
|
||||
isChildConversation &&
|
||||
this.shouldSuppressChildConversationNotification(notification.method)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const textDelta =
|
||||
notification.method === "item/agentMessage/delta"
|
||||
? this.readString(notification.params, "delta")
|
||||
@@ -1134,8 +1151,10 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
threadId: context.session.threadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: notification.method,
|
||||
turnId: route.turnId,
|
||||
itemId: route.itemId,
|
||||
...((childParentTurnId ?? rawRoute.turnId)
|
||||
? { turnId: childParentTurnId ?? rawRoute.turnId }
|
||||
: {}),
|
||||
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
|
||||
textDelta,
|
||||
payload: notification.params,
|
||||
});
|
||||
@@ -1151,6 +1170,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (notification.method === "turn/started") {
|
||||
if (isChildConversation) {
|
||||
return;
|
||||
}
|
||||
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
|
||||
this.updateSession(context, {
|
||||
status: "running",
|
||||
@@ -1160,6 +1182,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (notification.method === "turn/completed") {
|
||||
if (isChildConversation) {
|
||||
return;
|
||||
}
|
||||
context.collabReceiverTurns.clear();
|
||||
context.collabReceiverItems.clear();
|
||||
const turn = this.readObject(notification.params, "turn");
|
||||
const status = this.readString(turn, "status");
|
||||
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
|
||||
@@ -1172,6 +1199,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (notification.method === "error") {
|
||||
if (isChildConversation) {
|
||||
return;
|
||||
}
|
||||
const message = this.readString(this.readObject(notification.params)?.error, "message");
|
||||
const willRetry = this.readBoolean(notification.params, "willRetry");
|
||||
|
||||
@@ -1183,7 +1213,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
|
||||
const route = this.readRouteFields(request.params);
|
||||
const rawRoute = this.readRouteFields(request.params);
|
||||
const childParentTurnId = this.readChildParentTurnId(context, request.params);
|
||||
const childParentItemId = this.readChildParentItemId(context, request.params);
|
||||
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
|
||||
const effectiveItemId = rawRoute.itemId ?? childParentItemId;
|
||||
const requestKind = this.requestKindForMethod(request.method);
|
||||
let requestId: ApprovalRequestId | undefined;
|
||||
if (requestKind) {
|
||||
@@ -1199,8 +1233,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
: "item/fileChange/requestApproval",
|
||||
requestKind,
|
||||
threadId: context.session.threadId,
|
||||
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||
...(route.itemId ? { itemId: route.itemId } : {}),
|
||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
||||
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
|
||||
};
|
||||
context.pendingApprovals.set(requestId, pendingRequest);
|
||||
}
|
||||
@@ -1211,8 +1245,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
threadId: context.session.threadId,
|
||||
...(route.turnId ? { turnId: route.turnId } : {}),
|
||||
...(route.itemId ? { itemId: route.itemId } : {}),
|
||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
||||
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1223,8 +1257,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
threadId: context.session.threadId,
|
||||
createdAt: new Date().toISOString(),
|
||||
method: request.method,
|
||||
turnId: route.turnId,
|
||||
itemId: route.itemId,
|
||||
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
|
||||
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
|
||||
requestId,
|
||||
requestKind,
|
||||
payload: request.params,
|
||||
@@ -1451,6 +1485,79 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return route;
|
||||
}
|
||||
|
||||
private readProviderConversationId(params: unknown): string | undefined {
|
||||
return (
|
||||
this.readString(params, "threadId") ??
|
||||
this.readString(this.readObject(params, "thread"), "id") ??
|
||||
this.readString(params, "conversationId")
|
||||
);
|
||||
}
|
||||
|
||||
private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined {
|
||||
const providerConversationId = this.readProviderConversationId(params);
|
||||
if (!providerConversationId) {
|
||||
return undefined;
|
||||
}
|
||||
return context.collabReceiverTurns.get(providerConversationId);
|
||||
}
|
||||
|
||||
private readChildParentItemId(
|
||||
context: CodexSessionContext,
|
||||
params: unknown,
|
||||
): ProviderItemId | undefined {
|
||||
const providerConversationId = this.readProviderConversationId(params);
|
||||
if (!providerConversationId) {
|
||||
return undefined;
|
||||
}
|
||||
return context.collabReceiverItems.get(providerConversationId);
|
||||
}
|
||||
|
||||
private rememberCollabReceiverTurns(
|
||||
context: CodexSessionContext,
|
||||
params: unknown,
|
||||
parentTurnId: TurnId | undefined,
|
||||
): void {
|
||||
if (!parentTurnId) {
|
||||
return;
|
||||
}
|
||||
const payload = this.readObject(params);
|
||||
const item = this.readObject(payload, "item") ?? payload;
|
||||
const itemType = this.readString(item, "type") ?? this.readString(item, "kind");
|
||||
if (itemType !== "collabAgentToolCall") {
|
||||
return;
|
||||
}
|
||||
const parentItemId = toProviderItemId(this.readString(item, "id"));
|
||||
|
||||
const receiverThreadIds =
|
||||
this.readArray(item, "receiverThreadIds")
|
||||
?.map((value) => (typeof value === "string" ? value : null))
|
||||
.filter((value): value is string => value !== null) ?? [];
|
||||
for (const receiverThreadId of receiverThreadIds) {
|
||||
context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
|
||||
if (parentItemId) {
|
||||
context.collabReceiverItems.set(receiverThreadId, parentItemId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private shouldSuppressChildConversationNotification(method: string): boolean {
|
||||
return (
|
||||
method === "thread/started" ||
|
||||
method === "thread/status/changed" ||
|
||||
method === "thread/archived" ||
|
||||
method === "thread/unarchived" ||
|
||||
method === "thread/closed" ||
|
||||
method === "thread/compacted" ||
|
||||
method === "thread/name/updated" ||
|
||||
method === "thread/tokenUsage/updated" ||
|
||||
method === "turn/started" ||
|
||||
method === "turn/completed" ||
|
||||
method === "turn/aborted" ||
|
||||
method === "turn/plan/updated" ||
|
||||
method === "item/plan/delta"
|
||||
);
|
||||
}
|
||||
|
||||
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
|
||||
const target =
|
||||
key === undefined
|
||||
|
||||
@@ -3,6 +3,7 @@ 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";
|
||||
@@ -17,7 +18,6 @@ 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,6 +187,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
outputSchemaJson,
|
||||
imagePaths = [],
|
||||
cleanupPaths = [],
|
||||
model,
|
||||
}: {
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
cwd: string;
|
||||
@@ -194,6 +195,7 @@ 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(
|
||||
@@ -212,7 +214,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
CODEX_MODEL,
|
||||
model ?? DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
"--output-schema",
|
||||
@@ -353,6 +355,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson,
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
@@ -398,6 +401,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
title: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
}).pipe(
|
||||
Effect.map(
|
||||
(generated) =>
|
||||
@@ -449,6 +453,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
branch: Schema.String,
|
||||
}),
|
||||
imagePaths,
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -639,6 +639,7 @@ 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);
|
||||
@@ -665,6 +666,7 @@ 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)));
|
||||
|
||||
@@ -682,6 +684,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
commitMessage?: string,
|
||||
preResolvedSuggestion?: CommitAndBranchSuggestion,
|
||||
filePaths?: readonly string[],
|
||||
model?: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion =
|
||||
@@ -691,6 +694,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(model ? { model } : {}),
|
||||
}));
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
@@ -704,7 +708,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const runPrStep = (cwd: string, fallbackBranch: string | null) =>
|
||||
const runPrStep = (cwd: string, fallbackBranch: string | null, model?: string) =>
|
||||
Effect.gen(function* () {
|
||||
const details = yield* gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
@@ -748,6 +752,7 @@ 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`);
|
||||
@@ -972,6 +977,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
filePaths?: readonly string[],
|
||||
model?: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion = yield* resolveCommitAndBranchSuggestion({
|
||||
@@ -980,6 +986,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
includeBranch: true,
|
||||
...(model ? { model } : {}),
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* gitManagerError(
|
||||
@@ -1028,6 +1035,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
@@ -1044,6 +1052,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
);
|
||||
|
||||
const push = wantsPush
|
||||
@@ -1051,7 +1060,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? yield* runPrStep(input.cwd, currentBranch)
|
||||
? yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return {
|
||||
|
||||
@@ -19,6 +19,8 @@ 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 {
|
||||
@@ -35,6 +37,8 @@ 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 {
|
||||
@@ -46,6 +50,8 @@ 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 {
|
||||
|
||||
@@ -89,6 +89,7 @@ const make = Effect.gen(function* () {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: null,
|
||||
workUnitId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
@@ -113,6 +114,7 @@ const make = Effect.gen(function* () {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
workUnitId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
@@ -313,6 +315,7 @@ const make = Effect.gen(function* () {
|
||||
status: input.status,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
workUnitId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WorkUnitId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
@@ -175,6 +176,138 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("projects work units and activity work-unit links", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.created",
|
||||
eventId: EventId.makeUnsafe("evt-work-unit-thread"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-work-unit-thread"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-work-unit-thread"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread work unit",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.work-unit-upserted",
|
||||
eventId: EventId.makeUnsafe("evt-work-unit-upsert"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-work-unit-upsert"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-work-unit-upsert"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
workUnit: {
|
||||
id: WorkUnitId.makeUnsafe("wu:thread-work-unit:turn:turn-1:root"),
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
parentWorkUnitId: null,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
detail: null,
|
||||
spawnedByActivityId: null,
|
||||
providerRefs: {
|
||||
providerTurnId: "provider-turn-1",
|
||||
},
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
completedAt: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.makeUnsafe("evt-work-unit-activity"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-work-unit-activity"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-work-unit-activity"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
activity: {
|
||||
id: EventId.makeUnsafe("activity-work-unit"),
|
||||
tone: "info",
|
||||
kind: "task.progress",
|
||||
summary: "Reasoning update",
|
||||
payload: {
|
||||
detail: "Looking around",
|
||||
},
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
workUnitId: WorkUnitId.makeUnsafe("wu:thread-work-unit:turn:turn-1:root"),
|
||||
createdAt: now,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const workUnitRows = yield* sql<{
|
||||
readonly workUnitId: string;
|
||||
readonly turnId: string;
|
||||
readonly state: string;
|
||||
readonly providerRefsJson: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
work_unit_id AS "workUnitId",
|
||||
turn_id AS "turnId",
|
||||
state,
|
||||
provider_refs_json AS "providerRefsJson"
|
||||
FROM projection_thread_work_units
|
||||
WHERE thread_id = 'thread-work-unit'
|
||||
`;
|
||||
assert.deepEqual(workUnitRows, [
|
||||
{
|
||||
workUnitId: "wu:thread-work-unit:turn:turn-1:root",
|
||||
turnId: "turn-1",
|
||||
state: "running",
|
||||
providerRefsJson: '{"providerTurnId":"provider-turn-1"}',
|
||||
},
|
||||
]);
|
||||
|
||||
const activityRows = yield* sql<{
|
||||
readonly activityId: string;
|
||||
readonly workUnitId: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
activity_id AS "activityId",
|
||||
work_unit_id AS "workUnitId"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = 'thread-work-unit'
|
||||
`;
|
||||
assert.deepEqual(activityRows, [
|
||||
{
|
||||
activityId: "activity-work-unit",
|
||||
workUnitId: "wu:thread-work-unit:turn:turn-1:root",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stores message attachment references without mutating payloads", () =>
|
||||
Effect.sync(() => fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-"))).pipe(
|
||||
Effect.flatMap((stateDir) =>
|
||||
@@ -1729,6 +1862,8 @@ 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";
|
||||
|
||||
@@ -1749,6 +1884,10 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
payload: {
|
||||
threadId,
|
||||
messageId,
|
||||
sourceProposedPlan: {
|
||||
threadId: sourcePlanThreadId,
|
||||
planId: sourcePlanId,
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: turnStartedAt,
|
||||
},
|
||||
@@ -1800,11 +1939,15 @@ 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}
|
||||
@@ -1815,6 +1958,8 @@ 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,
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -22,6 +22,10 @@ import {
|
||||
type ProjectionThreadProposedPlan,
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
} from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
|
||||
import {
|
||||
type ProjectionThreadWorkUnit,
|
||||
ProjectionThreadWorkUnitRepository,
|
||||
} from "../../persistence/Services/ProjectionThreadWorkUnits.ts";
|
||||
import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import {
|
||||
type ProjectionTurn,
|
||||
@@ -34,6 +38,7 @@ import { ProjectionStateRepositoryLive } from "../../persistence/Layers/Projecti
|
||||
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionThreadWorkUnitRepositoryLive } from "../../persistence/Layers/ProjectionThreadWorkUnits.ts";
|
||||
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
||||
@@ -55,6 +60,7 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
threadMessages: "projection.thread-messages",
|
||||
threadProposedPlans: "projection.thread-proposed-plans",
|
||||
threadActivities: "projection.thread-activities",
|
||||
threadWorkUnits: "projection.thread-work-units",
|
||||
threadSessions: "projection.thread-sessions",
|
||||
threadTurns: "projection.thread-turns",
|
||||
checkpoints: "projection.checkpoints",
|
||||
@@ -214,6 +220,28 @@ function retainProjectionProposedPlansAfterRevert(
|
||||
);
|
||||
}
|
||||
|
||||
function retainProjectionWorkUnitsAfterRevert(
|
||||
workUnits: ReadonlyArray<ProjectionThreadWorkUnit>,
|
||||
turns: ReadonlyArray<ProjectionTurn>,
|
||||
turnCount: number,
|
||||
): ReadonlyArray<ProjectionThreadWorkUnit> {
|
||||
const retainedTurnIds = new Set<string>(
|
||||
turns
|
||||
.filter(
|
||||
(turn) =>
|
||||
turn.turnId !== null &&
|
||||
turn.checkpointTurnCount !== null &&
|
||||
turn.checkpointTurnCount <= turnCount,
|
||||
)
|
||||
.flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),
|
||||
);
|
||||
const retained = workUnits.filter((workUnit) => retainedTurnIds.has(workUnit.turnId));
|
||||
const retainedIds = new Set(retained.map((workUnit) => workUnit.workUnitId));
|
||||
return retained.filter(
|
||||
(workUnit) => workUnit.parentWorkUnitId === null || retainedIds.has(workUnit.parentWorkUnitId),
|
||||
);
|
||||
}
|
||||
|
||||
function collectThreadAttachmentRelativePaths(
|
||||
threadId: string,
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
@@ -346,6 +374,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
|
||||
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
|
||||
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
|
||||
const projectionThreadWorkUnitRepository = yield* ProjectionThreadWorkUnitRepository;
|
||||
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||
@@ -653,6 +682,8 @@ 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,
|
||||
});
|
||||
@@ -703,6 +734,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
activityId: event.payload.activity.id,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.activity.turnId,
|
||||
workUnitId: event.payload.activity.workUnitId,
|
||||
tone: event.payload.activity.tone,
|
||||
kind: event.payload.activity.kind,
|
||||
summary: event.payload.activity.summary,
|
||||
@@ -746,6 +778,64 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadWorkUnitsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.work-unit-upserted":
|
||||
yield* projectionThreadWorkUnitRepository.upsert({
|
||||
workUnitId: event.payload.workUnit.id,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.workUnit.turnId,
|
||||
parentWorkUnitId: event.payload.workUnit.parentWorkUnitId,
|
||||
kind: event.payload.workUnit.kind,
|
||||
state: event.payload.workUnit.state,
|
||||
title: event.payload.workUnit.title,
|
||||
detail: event.payload.workUnit.detail,
|
||||
spawnedByActivityId: event.payload.workUnit.spawnedByActivityId,
|
||||
...(event.payload.workUnit.providerRefs !== undefined
|
||||
? { providerRefs: event.payload.workUnit.providerRefs }
|
||||
: {}),
|
||||
startedAt: event.payload.workUnit.startedAt,
|
||||
updatedAt: event.payload.workUnit.updatedAt,
|
||||
completedAt: event.payload.workUnit.completedAt,
|
||||
});
|
||||
return;
|
||||
|
||||
case "thread.reverted": {
|
||||
const existingRows = yield* projectionThreadWorkUnitRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (existingRows.length === 0) {
|
||||
return;
|
||||
}
|
||||
const existingTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const keptRows = retainProjectionWorkUnitsAfterRevert(
|
||||
existingRows,
|
||||
existingTurns,
|
||||
event.payload.turnCount,
|
||||
);
|
||||
if (keptRows.length === existingRows.length) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadWorkUnitRepository.deleteByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
yield* Effect.forEach(keptRows, projectionThreadWorkUnitRepository.upsert, {
|
||||
concurrency: 1,
|
||||
}).pipe(Effect.asVoid);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
@@ -775,6 +865,8 @@ 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;
|
||||
@@ -804,6 +896,16 @@ 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)
|
||||
@@ -822,6 +924,12 @@ 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)
|
||||
@@ -875,6 +983,8 @@ 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,
|
||||
@@ -910,6 +1020,8 @@ 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,
|
||||
@@ -954,6 +1066,8 @@ 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,
|
||||
@@ -1108,6 +1222,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
apply: applyThreadActivitiesProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadWorkUnits,
|
||||
apply: applyThreadWorkUnitsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||
apply: applyThreadSessionsProjection,
|
||||
@@ -1225,6 +1343,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadWorkUnitRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
|
||||
Layer.provideMerge(ProjectionTurnRepositoryLive),
|
||||
Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
CheckpointRef,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WorkUnitId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -13,6 +21,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||
const asWorkUnitId = (value: string): WorkUnitId => WorkUnitId.makeUnsafe(value);
|
||||
|
||||
const projectionSnapshotLayer = it.layer(
|
||||
OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
@@ -26,6 +35,7 @@ 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`
|
||||
@@ -101,11 +111,35 @@ 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,
|
||||
thread_id,
|
||||
turn_id,
|
||||
work_unit_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
@@ -116,6 +150,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'activity-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'wu:thread-1:turn:turn-1:root',
|
||||
'info',
|
||||
'runtime.note',
|
||||
'provider started',
|
||||
@@ -124,6 +159,39 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_work_units (
|
||||
work_unit_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
parent_work_unit_id,
|
||||
kind,
|
||||
state,
|
||||
title,
|
||||
detail,
|
||||
spawned_by_activity_id,
|
||||
provider_refs_json,
|
||||
started_at,
|
||||
updated_at,
|
||||
completed_at
|
||||
)
|
||||
VALUES (
|
||||
'wu:thread-1:turn:turn-1:root',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'primary_agent',
|
||||
'completed',
|
||||
'Primary agent',
|
||||
NULL,
|
||||
NULL,
|
||||
'{"providerTurnId":"provider-turn-1"}',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
'2026-02-24T00:00:08.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_sessions (
|
||||
thread_id,
|
||||
@@ -154,6 +222,8 @@ 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,
|
||||
@@ -168,6 +238,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'thread-1',
|
||||
'plan-1',
|
||||
'message-1',
|
||||
'completed',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
@@ -238,6 +310,10 @@ 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",
|
||||
@@ -253,7 +329,17 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
updatedAt: "2026-02-24T00:00:05.000Z",
|
||||
},
|
||||
],
|
||||
proposedPlans: [],
|
||||
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",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
{
|
||||
id: asEventId("activity-1"),
|
||||
@@ -262,9 +348,28 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
summary: "provider started",
|
||||
payload: { stage: "start" },
|
||||
turnId: asTurnId("turn-1"),
|
||||
workUnitId: asWorkUnitId("wu:thread-1:turn:turn-1:root"),
|
||||
createdAt: "2026-02-24T00:00:06.000Z",
|
||||
},
|
||||
],
|
||||
workUnits: [
|
||||
{
|
||||
id: asWorkUnitId("wu:thread-1:turn:turn-1:root"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
parentWorkUnitId: null,
|
||||
kind: "primary_agent",
|
||||
state: "completed",
|
||||
title: "Primary agent",
|
||||
detail: null,
|
||||
spawnedByActivityId: null,
|
||||
providerRefs: {
|
||||
providerTurnId: "provider-turn-1",
|
||||
},
|
||||
startedAt: "2026-02-24T00:00:08.000Z",
|
||||
updatedAt: "2026-02-24T00:00:08.000Z",
|
||||
completedAt: "2026-02-24T00:00:08.000Z",
|
||||
},
|
||||
],
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: asTurnId("turn-1"),
|
||||
|
||||
@@ -4,8 +4,10 @@ import {
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationReadModel,
|
||||
ProjectScript,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationLatestTurn,
|
||||
@@ -15,6 +17,7 @@ import {
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
type OrchestrationWorkUnit,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -32,6 +35,7 @@ import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
|
||||
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionThreadWorkUnit } from "../../persistence/Services/ProjectionThreadWorkUnits.ts";
|
||||
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
|
||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
@@ -60,6 +64,13 @@ const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
sequence: Schema.NullOr(NonNegativeInt),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadWorkUnitDbRowSchema = ProjectionThreadWorkUnit.mapFields(
|
||||
Struct.assign({
|
||||
providerRefs: Schema.NullOr(
|
||||
Schema.fromJsonString(ProjectionThreadWorkUnit.fields.providerRefs),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;
|
||||
const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
|
||||
Struct.assign({
|
||||
@@ -74,6 +85,8 @@ 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;
|
||||
|
||||
@@ -83,6 +96,7 @@ const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadWorkUnits,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
|
||||
] as const;
|
||||
@@ -200,6 +214,8 @@ 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
|
||||
@@ -216,6 +232,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
work_unit_id AS "workUnitId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
@@ -232,6 +249,30 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadWorkUnitRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadWorkUnitDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
work_unit_id AS "workUnitId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
parent_work_unit_id AS "parentWorkUnitId",
|
||||
kind,
|
||||
state,
|
||||
title,
|
||||
detail,
|
||||
spawned_by_activity_id AS "spawnedByActivityId",
|
||||
provider_refs_json AS "providerRefs",
|
||||
started_at AS "startedAt",
|
||||
updated_at AS "updatedAt",
|
||||
completed_at AS "completedAt"
|
||||
FROM projection_thread_work_units
|
||||
ORDER BY thread_id ASC, started_at ASC, work_unit_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadSessionRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadSessionDbRowSchema,
|
||||
@@ -284,7 +325,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
requested_at AS "requestedAt",
|
||||
started_at AS "startedAt",
|
||||
completed_at AS "completedAt",
|
||||
assistant_message_id AS "assistantMessageId"
|
||||
assistant_message_id AS "assistantMessageId",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId"
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NOT NULL
|
||||
ORDER BY thread_id ASC, requested_at DESC, turn_id DESC
|
||||
@@ -314,6 +357,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
activityRows,
|
||||
workUnitRows,
|
||||
sessionRows,
|
||||
checkpointRows,
|
||||
latestTurnRows,
|
||||
@@ -359,6 +403,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadWorkUnitRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadWorkUnits:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadWorkUnits:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadSessionRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -396,6 +448,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
|
||||
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
|
||||
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
||||
const workUnitsByThread = new Map<string, Array<OrchestrationWorkUnit>>();
|
||||
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
||||
const sessionsByThread = new Map<string, OrchestrationSession>();
|
||||
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
|
||||
@@ -435,6 +488,8 @@ 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,
|
||||
});
|
||||
@@ -451,12 +506,33 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
workUnitId: row.workUnitId,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
});
|
||||
activitiesByThread.set(row.threadId, threadActivities);
|
||||
}
|
||||
|
||||
for (const row of workUnitRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
const threadWorkUnits = workUnitsByThread.get(row.threadId) ?? [];
|
||||
threadWorkUnits.push({
|
||||
id: row.workUnitId,
|
||||
turnId: row.turnId,
|
||||
parentWorkUnitId: row.parentWorkUnitId,
|
||||
kind: row.kind,
|
||||
state: row.state,
|
||||
title: row.title,
|
||||
detail: row.detail,
|
||||
spawnedByActivityId: row.spawnedByActivityId,
|
||||
...(row.providerRefs !== null ? { providerRefs: row.providerRefs } : {}),
|
||||
startedAt: row.startedAt,
|
||||
updatedAt: row.updatedAt,
|
||||
completedAt: row.completedAt,
|
||||
});
|
||||
workUnitsByThread.set(row.threadId, threadWorkUnits);
|
||||
}
|
||||
|
||||
for (const row of checkpointRows) {
|
||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
||||
const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];
|
||||
@@ -497,6 +573,14 @@ 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,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -540,6 +624,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
workUnits: workUnitsByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
}));
|
||||
|
||||
@@ -83,9 +83,13 @@ describe("ProviderCommandReactor", () => {
|
||||
createdStateDirs.clear();
|
||||
});
|
||||
|
||||
async function createHarness(input?: { readonly stateDir?: string }) {
|
||||
async function createHarness(input?: {
|
||||
readonly stateDir?: string;
|
||||
readonly threadModel?: string;
|
||||
}) {
|
||||
const now = new Date().toISOString();
|
||||
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||
const threadModel = input?.threadModel ?? "gpt-5-codex";
|
||||
createdStateDirs.add(stateDir);
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
let nextSessionIndex = 1;
|
||||
@@ -228,7 +232,7 @@ describe("ProviderCommandReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModel: threadModel,
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -239,7 +243,7 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
model: threadModel,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -352,7 +356,7 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
it("forwards claude effort options through session start and turn send", async () => {
|
||||
const harness = await createHarness();
|
||||
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -401,6 +405,56 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards claude fast mode options through session start and turn send", async () => {
|
||||
const harness = await createHarness({ threadModel: "claude-opus-4-6" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-claude-fast-mode"),
|
||||
role: "user",
|
||||
text: "hello with fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards plan interaction mode to the provider turn request", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -582,7 +636,7 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
it("restarts claude sessions when claude effort changes", async () => {
|
||||
const harness = await createHarness();
|
||||
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -1043,6 +1097,7 @@ describe("ProviderCommandReactor", () => {
|
||||
requestKind: "command",
|
||||
},
|
||||
turnId: null,
|
||||
workUnitId: null,
|
||||
createdAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
type ChatAttachment,
|
||||
CommandId,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderModelOptions,
|
||||
@@ -75,23 +76,10 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
|
||||
function structuralEqual(a: unknown, b: unknown): boolean {
|
||||
if (a === b) return true;
|
||||
if (a == null || b == null) return a === b;
|
||||
if (typeof a !== typeof b) return false;
|
||||
if (typeof a !== "object") return false;
|
||||
const objA = a as Record<string, unknown>;
|
||||
const objB = b as Record<string, unknown>;
|
||||
const keysA = Object.keys(objA).filter((k) => objA[k] !== undefined);
|
||||
const keysB = Object.keys(objB).filter((k) => objB[k] !== undefined);
|
||||
if (keysA.length !== keysB.length) return false;
|
||||
return keysA.every((key) => objB[key] !== undefined && structuralEqual(objA[key], objB[key]));
|
||||
}
|
||||
|
||||
const sameModelOptions = (
|
||||
left: ProviderModelOptions | undefined,
|
||||
right: ProviderModelOptions | undefined,
|
||||
): boolean => structuralEqual(left ?? null, right ?? null);
|
||||
): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
|
||||
|
||||
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = Cause.squash(cause);
|
||||
@@ -185,6 +173,7 @@ const make = Effect.gen(function* () {
|
||||
...(input.requestId ? { requestId: input.requestId } : {}),
|
||||
},
|
||||
turnId: input.turnId,
|
||||
workUnitId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
@@ -446,6 +435,7 @@ const make = Effect.gen(function* () {
|
||||
cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
OrchestrationReadModel,
|
||||
ProviderKind,
|
||||
ProviderRuntimeEvent,
|
||||
ProviderSession,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -61,6 +62,7 @@ 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 = {
|
||||
@@ -70,12 +72,21 @@ function createProviderServiceHarness() {
|
||||
respondToRequest: () => unsupported(),
|
||||
respondToUserInput: () => unsupported(),
|
||||
stopSession: () => unsupported(),
|
||||
listSessions: () => Effect.succeed([]),
|
||||
listSessions: () => Effect.succeed([...runtimeSessions]),
|
||||
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));
|
||||
};
|
||||
@@ -83,6 +94,7 @@ function createProviderServiceHarness() {
|
||||
return {
|
||||
service,
|
||||
emit,
|
||||
setSession,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -90,11 +102,12 @@ 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.makeUnsafe("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
@@ -112,6 +125,7 @@ type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number]
|
||||
type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
|
||||
type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
|
||||
type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
|
||||
type ProviderRuntimeTestWorkUnit = ProviderRuntimeTestThread["workUnits"][number];
|
||||
type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
|
||||
|
||||
describe("ProviderRuntimeIngestion", () => {
|
||||
@@ -154,6 +168,7 @@ 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),
|
||||
@@ -209,10 +224,19 @@ 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,
|
||||
};
|
||||
}
|
||||
@@ -686,6 +710,496 @@ 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();
|
||||
@@ -1396,6 +1910,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-task-1"),
|
||||
itemId: "call-collab-1",
|
||||
payload: {
|
||||
taskId: "turn-task-1",
|
||||
taskType: "plan",
|
||||
@@ -1409,6 +1924,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-task-1"),
|
||||
itemId: "call-collab-1",
|
||||
payload: {
|
||||
taskId: "turn-task-1",
|
||||
description: "Comparing the desktop rollout chunks to the app-server stream.",
|
||||
@@ -1423,6 +1939,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-task-1"),
|
||||
itemId: "call-collab-1",
|
||||
payload: {
|
||||
taskId: "turn-task-1",
|
||||
status: "completed",
|
||||
@@ -1481,6 +1998,38 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
expect(completed?.kind).toBe("task.completed");
|
||||
expect(completedPayload?.detail).toBe("<proposed_plan>\n# Plan title\n</proposed_plan>");
|
||||
expect(started?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
|
||||
expect(progress?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
|
||||
expect(completed?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
|
||||
expect(
|
||||
thread.workUnits.find(
|
||||
(entry: ProviderRuntimeTestWorkUnit) => entry.id === "wu:thread-1:turn:turn-task-1:root",
|
||||
),
|
||||
).toMatchObject({
|
||||
id: "wu:thread-1:turn:turn-task-1:root",
|
||||
turnId: "turn-task-1",
|
||||
parentWorkUnitId: null,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
});
|
||||
expect(
|
||||
thread.workUnits.find(
|
||||
(entry: ProviderRuntimeTestWorkUnit) =>
|
||||
entry.id === "wu:thread-1:turn:turn-task-1:task:turn-task-1",
|
||||
),
|
||||
).toMatchObject({
|
||||
id: "wu:thread-1:turn:turn-task-1:task:turn-task-1",
|
||||
turnId: "turn-task-1",
|
||||
parentWorkUnitId: "wu:thread-1:turn:turn-task-1:root",
|
||||
kind: "delegated_agent",
|
||||
state: "completed",
|
||||
title: "<proposed_plan>\n# Plan title\n</proposed_plan>",
|
||||
providerRefs: {
|
||||
runtimeTaskId: "turn-task-1",
|
||||
runtimeItemId: "call-collab-1",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
thread.proposedPlans.find(
|
||||
(entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-task-1",
|
||||
|
||||
@@ -4,10 +4,14 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationProposedPlanId,
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
RuntimeTaskId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WorkUnitId,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -15,6 +19,8 @@ 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";
|
||||
@@ -26,6 +32,10 @@ import {
|
||||
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
|
||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
|
||||
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
||||
const rootWorkUnitIdForTurn = (threadId: ThreadId, turnId: TurnId): WorkUnitId =>
|
||||
WorkUnitId.makeUnsafe(`wu:${threadId}:turn:${turnId}:root`);
|
||||
const taskWorkUnitIdForTurn = (threadId: ThreadId, turnId: TurnId, taskId: string): WorkUnitId =>
|
||||
WorkUnitId.makeUnsafe(`wu:${threadId}:turn:${turnId}:task:${taskId}`);
|
||||
|
||||
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
|
||||
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
|
||||
@@ -174,6 +184,57 @@ function requestKindFromCanonicalRequestType(
|
||||
}
|
||||
}
|
||||
|
||||
function workUnitIdForRuntimeEvent(event: ProviderRuntimeEvent): WorkUnitId | null {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
event.type === "task.started" ||
|
||||
event.type === "task.progress" ||
|
||||
event.type === "task.completed"
|
||||
) {
|
||||
return taskWorkUnitIdForTurn(event.threadId, turnId, String(event.payload.taskId));
|
||||
}
|
||||
return rootWorkUnitIdForTurn(event.threadId, turnId);
|
||||
}
|
||||
|
||||
function runtimeTurnStateToWorkUnitState(
|
||||
state: "completed" | "failed" | "interrupted" | "cancelled",
|
||||
): "completed" | "failed" | "stopped" | "cancelled" {
|
||||
switch (state) {
|
||||
case "failed":
|
||||
return "failed";
|
||||
case "interrupted":
|
||||
return "stopped";
|
||||
case "cancelled":
|
||||
return "cancelled";
|
||||
case "completed":
|
||||
return "completed";
|
||||
}
|
||||
}
|
||||
|
||||
function runtimeTaskStateToWorkUnitState(
|
||||
state: "completed" | "failed" | "stopped",
|
||||
): "completed" | "failed" | "stopped" {
|
||||
switch (state) {
|
||||
case "failed":
|
||||
return "failed";
|
||||
case "stopped":
|
||||
return "stopped";
|
||||
case "completed":
|
||||
return "completed";
|
||||
}
|
||||
}
|
||||
|
||||
function providerTurnWorkUnitRefs(
|
||||
event: ProviderRuntimeEvent,
|
||||
): NonNullable<OrchestrationThread["workUnits"][number]["providerRefs"]> | undefined {
|
||||
return event.providerRefs?.providerTurnId !== undefined
|
||||
? { providerTurnId: event.providerRefs.providerTurnId }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function runtimeEventToActivities(
|
||||
event: ProviderRuntimeEvent,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
@@ -183,6 +244,7 @@ function runtimeEventToActivities(
|
||||
? { sequence: eventWithSequence.sessionSequence }
|
||||
: {};
|
||||
})();
|
||||
const maybeWorkUnit = { workUnitId: workUnitIdForRuntimeEvent(event) };
|
||||
switch (event.type) {
|
||||
case "request.opened": {
|
||||
if (event.payload.requestType === "tool_user_input") {
|
||||
@@ -210,6 +272,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -234,6 +297,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.decision ? { decision: event.payload.decision } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -255,6 +319,7 @@ function runtimeEventToActivities(
|
||||
message: truncateDetail(message),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -273,6 +338,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -293,6 +359,7 @@ function runtimeEventToActivities(
|
||||
: {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -311,6 +378,7 @@ function runtimeEventToActivities(
|
||||
questions: event.payload.questions,
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -329,6 +397,7 @@ function runtimeEventToActivities(
|
||||
answers: event.payload.answers,
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -355,6 +424,7 @@ function runtimeEventToActivities(
|
||||
: {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -376,6 +446,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -401,6 +472,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -424,6 +496,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -445,6 +518,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -466,6 +540,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -481,6 +556,7 @@ 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,
|
||||
@@ -672,6 +748,8 @@ const make = Effect.gen(function* () {
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
@@ -694,6 +772,8 @@ 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,
|
||||
},
|
||||
@@ -707,6 +787,8 @@ const make = Effect.gen(function* () {
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
@@ -773,6 +855,147 @@ 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 upsertWorkUnit = Effect.fnUntraced(function* (input: {
|
||||
thread: OrchestrationThread;
|
||||
event: ProviderRuntimeEvent;
|
||||
workUnitId: WorkUnitId;
|
||||
turnId: TurnId;
|
||||
kind: "primary_agent" | "delegated_agent";
|
||||
state: "queued" | "running" | "completed" | "failed" | "stopped" | "cancelled";
|
||||
title: string;
|
||||
updatedAt: string;
|
||||
parentWorkUnitId?: WorkUnitId | null;
|
||||
detail?: string | null;
|
||||
startedAt?: string;
|
||||
completedAt?: string | null;
|
||||
providerRefs?: NonNullable<OrchestrationThread["workUnits"][number]["providerRefs"]>;
|
||||
}) {
|
||||
const existing = input.thread.workUnits.find((entry) => sameId(entry.id, input.workUnitId));
|
||||
const providerRefs =
|
||||
input.providerRefs !== undefined || existing?.providerRefs !== undefined
|
||||
? {
|
||||
...existing?.providerRefs,
|
||||
...input.providerRefs,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.work-unit.upsert",
|
||||
commandId: providerCommandId(input.event, "thread-work-unit-upsert"),
|
||||
threadId: input.thread.id,
|
||||
workUnit: {
|
||||
id: input.workUnitId,
|
||||
turnId: input.turnId,
|
||||
parentWorkUnitId: input.parentWorkUnitId ?? existing?.parentWorkUnitId ?? null,
|
||||
kind: input.kind,
|
||||
state: input.state,
|
||||
title: input.title.trim().length > 0 ? input.title : (existing?.title ?? "Work unit"),
|
||||
detail: input.detail !== undefined ? input.detail : (existing?.detail ?? null),
|
||||
spawnedByActivityId: existing?.spawnedByActivityId ?? null,
|
||||
...(providerRefs !== undefined ? { providerRefs } : {}),
|
||||
startedAt: existing?.startedAt ?? input.startedAt ?? input.updatedAt,
|
||||
updatedAt: input.updatedAt,
|
||||
completedAt:
|
||||
input.completedAt !== undefined ? input.completedAt : (existing?.completedAt ?? null),
|
||||
},
|
||||
createdAt: input.updatedAt,
|
||||
});
|
||||
});
|
||||
|
||||
const ensureRootWorkUnit = Effect.fnUntraced(function* (
|
||||
thread: OrchestrationThread,
|
||||
event: ProviderRuntimeEvent,
|
||||
turnId: TurnId,
|
||||
updatedAt: string,
|
||||
) {
|
||||
const providerRefs = providerTurnWorkUnitRefs(event);
|
||||
yield* upsertWorkUnit({
|
||||
thread,
|
||||
event,
|
||||
workUnitId: rootWorkUnitIdForTurn(thread.id, turnId),
|
||||
turnId,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
updatedAt,
|
||||
startedAt: updatedAt,
|
||||
...(providerRefs ? { providerRefs } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -813,6 +1036,10 @@ 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" ||
|
||||
@@ -855,6 +1082,26 @@ 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"),
|
||||
@@ -873,6 +1120,89 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
if (eventTurnId !== undefined) {
|
||||
yield* ensureRootWorkUnit(thread, event, eventTurnId, now);
|
||||
}
|
||||
|
||||
if (event.type === "turn.started" && eventTurnId !== undefined) {
|
||||
const providerRefs = providerTurnWorkUnitRefs(event);
|
||||
yield* upsertWorkUnit({
|
||||
thread,
|
||||
event,
|
||||
workUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
|
||||
turnId: eventTurnId,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
updatedAt: now,
|
||||
startedAt: now,
|
||||
...(providerRefs ? { providerRefs } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed" && eventTurnId !== undefined) {
|
||||
const providerRefs = providerTurnWorkUnitRefs(event);
|
||||
yield* upsertWorkUnit({
|
||||
thread,
|
||||
event,
|
||||
workUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
|
||||
turnId: eventTurnId,
|
||||
kind: "primary_agent",
|
||||
state: runtimeTurnStateToWorkUnitState(runtimeTurnState(event)),
|
||||
title: "Primary agent",
|
||||
updatedAt: now,
|
||||
completedAt: now,
|
||||
...(providerRefs ? { providerRefs } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
(event.type === "task.started" ||
|
||||
event.type === "task.progress" ||
|
||||
event.type === "task.completed") &&
|
||||
eventTurnId !== undefined
|
||||
) {
|
||||
const taskId = String(event.payload.taskId);
|
||||
const workUnitId = taskWorkUnitIdForTurn(thread.id, eventTurnId, taskId);
|
||||
const taskState =
|
||||
event.type === "task.completed"
|
||||
? runtimeTaskStateToWorkUnitState(event.payload.status)
|
||||
: "running";
|
||||
const taskTitle =
|
||||
event.type === "task.started"
|
||||
? (event.payload.description ?? event.payload.taskType ?? "Delegated task")
|
||||
: event.type === "task.completed"
|
||||
? (event.payload.summary ?? "Delegated task")
|
||||
: (event.payload.summary ?? event.payload.description);
|
||||
const taskDetail =
|
||||
event.type === "task.started"
|
||||
? (event.payload.description ?? null)
|
||||
: event.type === "task.completed"
|
||||
? (event.payload.summary ?? null)
|
||||
: (event.payload.summary ?? event.payload.description);
|
||||
yield* upsertWorkUnit({
|
||||
thread,
|
||||
event,
|
||||
workUnitId,
|
||||
turnId: eventTurnId,
|
||||
parentWorkUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
|
||||
kind: "delegated_agent",
|
||||
state: taskState,
|
||||
title: taskTitle,
|
||||
detail: taskDetail,
|
||||
updatedAt: now,
|
||||
...(event.type === "task.started" ? { startedAt: now } : {}),
|
||||
...(event.type === "task.completed" ? { completedAt: now } : {}),
|
||||
providerRefs: {
|
||||
runtimeTaskId: RuntimeTaskId.makeUnsafe(taskId),
|
||||
...(event.itemId ? { runtimeItemId: event.itemId } : {}),
|
||||
...(event.providerRefs?.providerTurnId !== undefined
|
||||
? { providerTurnId: event.providerRefs.providerTurnId }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const assistantDelta =
|
||||
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
|
||||
? event.payload.delta
|
||||
@@ -1145,4 +1475,7 @@ const make = Effect.gen(function* () {
|
||||
} satisfies ProviderRuntimeIngestionShape;
|
||||
});
|
||||
|
||||
export const ProviderRuntimeIngestionLive = Layer.effect(ProviderRuntimeIngestionService, make);
|
||||
export const ProviderRuntimeIngestionLive = Layer.effect(
|
||||
ProviderRuntimeIngestionService,
|
||||
make,
|
||||
).pipe(Layer.provide(ProjectionTurnRepositoryLive));
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
|
||||
ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,
|
||||
ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema,
|
||||
ThreadWorkUnitUpsertedPayload as ContractsThreadWorkUnitUpsertedPayloadSchema,
|
||||
ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema,
|
||||
ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema,
|
||||
ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema,
|
||||
@@ -37,6 +38,7 @@ export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
|
||||
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
|
||||
export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;
|
||||
export const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema;
|
||||
export const ThreadWorkUnitUpsertedPayload = ContractsThreadWorkUnitUpsertedPayloadSchema;
|
||||
|
||||
export const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema;
|
||||
export const ThreadTurnInterruptRequestedPayload =
|
||||
|
||||
@@ -62,6 +62,7 @@ const readModel: OrchestrationReadModel = {
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
},
|
||||
@@ -81,6 +82,7 @@ const readModel: OrchestrationReadModel = {
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
},
|
||||
|
||||
@@ -262,11 +262,35 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
}
|
||||
|
||||
case "thread.turn.start": {
|
||||
yield* requireThread({
|
||||
const targetThread = 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",
|
||||
@@ -306,12 +330,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
? { providerOptions: command.providerOptions }
|
||||
: {}),
|
||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
runtimeMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
|
||||
command.runtimeMode,
|
||||
interactionMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
|
||||
command.interactionMode,
|
||||
runtimeMode: targetThread.runtimeMode,
|
||||
interactionMode: targetThread.interactionMode,
|
||||
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
@@ -610,6 +631,27 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.work-unit.upsert": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.work-unit-upserted",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
workUnit: command.workUnit,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
default: {
|
||||
command satisfies never;
|
||||
const fallback = command as never as { type: string };
|
||||
|
||||
@@ -85,6 +85,7 @@ describe("orchestration projector", () => {
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
@@ -122,6 +123,88 @@ describe("orchestration projector", () => {
|
||||
).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
it("applies thread.work-unit-upserted events", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const model = createEmptyReadModel(now);
|
||||
|
||||
const afterCreate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: now,
|
||||
commandId: "cmd-thread-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const next = await Effect.runPromise(
|
||||
projectEvent(
|
||||
afterCreate,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.work-unit-upserted",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: now,
|
||||
commandId: "cmd-work-unit-upsert",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
workUnit: {
|
||||
id: "wu:thread-1:turn:turn-1:root",
|
||||
turnId: "turn-1",
|
||||
parentWorkUnitId: null,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
detail: null,
|
||||
spawnedByActivityId: null,
|
||||
providerRefs: {
|
||||
providerTurnId: "provider-turn-1",
|
||||
},
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
completedAt: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(next.threads[0]?.workUnits).toEqual([
|
||||
{
|
||||
id: "wu:thread-1:turn:turn-1:root",
|
||||
turnId: "turn-1",
|
||||
parentWorkUnitId: null,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
detail: null,
|
||||
spawnedByActivityId: null,
|
||||
providerRefs: {
|
||||
providerTurnId: "provider-turn-1",
|
||||
},
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
completedAt: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps projector forward-compatible for unhandled event types", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const model = createEmptyReadModel(now);
|
||||
@@ -453,6 +536,7 @@ describe("orchestration projector", () => {
|
||||
summary: "Edit file started",
|
||||
payload: { toolKind: "command" },
|
||||
turnId: "turn-1",
|
||||
workUnitId: null,
|
||||
createdAt: "2026-02-23T10:00:02.750Z",
|
||||
},
|
||||
},
|
||||
@@ -527,6 +611,7 @@ describe("orchestration projector", () => {
|
||||
summary: "Edit file complete",
|
||||
payload: { toolKind: "command" },
|
||||
turnId: "turn-2",
|
||||
workUnitId: null,
|
||||
createdAt: "2026-02-23T10:00:04.750Z",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
ThreadWorkUnitUpsertedPayload,
|
||||
} from "./Schemas.ts";
|
||||
|
||||
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
|
||||
@@ -136,6 +137,17 @@ function retainThreadProposedPlansAfterRevert(
|
||||
);
|
||||
}
|
||||
|
||||
function retainThreadWorkUnitsAfterRevert(
|
||||
workUnits: ReadonlyArray<OrchestrationThread["workUnits"][number]>,
|
||||
retainedTurnIds: ReadonlySet<string>,
|
||||
): ReadonlyArray<OrchestrationThread["workUnits"][number]> {
|
||||
const retained = workUnits.filter((workUnit) => retainedTurnIds.has(workUnit.turnId));
|
||||
const retainedIds = new Set(retained.map((workUnit) => workUnit.id));
|
||||
return retained.filter(
|
||||
(workUnit) => workUnit.parentWorkUnitId === null || retainedIds.has(workUnit.parentWorkUnitId),
|
||||
);
|
||||
}
|
||||
|
||||
function compareThreadActivities(
|
||||
left: OrchestrationThread["activities"][number],
|
||||
right: OrchestrationThread["activities"][number],
|
||||
@@ -262,7 +274,9 @@ export function projectEvent(
|
||||
updatedAt: payload.updatedAt,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
@@ -563,6 +577,7 @@ export function projectEvent(
|
||||
retainedTurnIds,
|
||||
).slice(-200);
|
||||
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
|
||||
const workUnits = retainThreadWorkUnitsAfterRevert(thread.workUnits, retainedTurnIds);
|
||||
|
||||
const latestCheckpoint = checkpoints.at(-1) ?? null;
|
||||
const latestTurn =
|
||||
@@ -584,6 +599,7 @@ export function projectEvent(
|
||||
messages,
|
||||
proposedPlans,
|
||||
activities,
|
||||
workUnits,
|
||||
latestTurn,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
@@ -621,6 +637,37 @@ export function projectEvent(
|
||||
}),
|
||||
);
|
||||
|
||||
case "thread.work-unit-upserted":
|
||||
return decodeForEvent(
|
||||
ThreadWorkUnitUpsertedPayload,
|
||||
event.payload,
|
||||
event.type,
|
||||
"payload",
|
||||
).pipe(
|
||||
Effect.map((payload) => {
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
|
||||
const workUnits = [
|
||||
...thread.workUnits.filter((entry) => entry.id !== payload.workUnit.id),
|
||||
payload.workUnit,
|
||||
].toSorted(
|
||||
(left, right) =>
|
||||
left.startedAt.localeCompare(right.startedAt) || left.id.localeCompare(right.id),
|
||||
);
|
||||
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
workUnits,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
default:
|
||||
return Effect.succeed(nextBase);
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
activity_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
work_unit_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
@@ -49,6 +50,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
${row.activityId},
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.workUnitId},
|
||||
${row.tone},
|
||||
${row.kind},
|
||||
${row.summary},
|
||||
@@ -60,6 +62,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
DO UPDATE SET
|
||||
thread_id = excluded.thread_id,
|
||||
turn_id = excluded.turn_id,
|
||||
work_unit_id = excluded.work_unit_id,
|
||||
tone = excluded.tone,
|
||||
kind = excluded.kind,
|
||||
summary = excluded.summary,
|
||||
@@ -78,6 +81,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
work_unit_id AS "workUnitId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
@@ -126,6 +130,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
activityId: row.activityId,
|
||||
threadId: row.threadId,
|
||||
turnId: row.turnId,
|
||||
workUnitId: row.workUnitId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
|
||||
@@ -22,6 +22,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
turn_id,
|
||||
plan_markdown,
|
||||
implemented_at,
|
||||
implementation_thread_id,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
@@ -30,6 +32,8 @@ const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.planMarkdown},
|
||||
${row.implementedAt},
|
||||
${row.implementationThreadId},
|
||||
${row.createdAt},
|
||||
${row.updatedAt}
|
||||
)
|
||||
@@ -38,6 +42,8 @@ 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
|
||||
`,
|
||||
@@ -52,6 +58,8 @@ 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
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
|
||||
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionThreadWorkUnitsInput,
|
||||
ListProjectionThreadWorkUnitsInput,
|
||||
ProjectionThreadWorkUnit,
|
||||
ProjectionThreadWorkUnitRepository,
|
||||
type ProjectionThreadWorkUnitRepositoryShape,
|
||||
} from "../Services/ProjectionThreadWorkUnits.ts";
|
||||
|
||||
const ProjectionThreadWorkUnitDbRowSchema = ProjectionThreadWorkUnit.mapFields(
|
||||
Struct.assign({
|
||||
providerRefs: Schema.NullOr(
|
||||
Schema.fromJsonString(ProjectionThreadWorkUnit.fields.providerRefs),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown) =>
|
||||
Schema.isSchemaError(cause)
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
const makeProjectionThreadWorkUnitRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertProjectionThreadWorkUnitRow = SqlSchema.void({
|
||||
Request: ProjectionThreadWorkUnit,
|
||||
execute: (row) => sql`
|
||||
INSERT INTO projection_thread_work_units (
|
||||
work_unit_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
parent_work_unit_id,
|
||||
kind,
|
||||
state,
|
||||
title,
|
||||
detail,
|
||||
spawned_by_activity_id,
|
||||
provider_refs_json,
|
||||
started_at,
|
||||
updated_at,
|
||||
completed_at
|
||||
)
|
||||
VALUES (
|
||||
${row.workUnitId},
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.parentWorkUnitId},
|
||||
${row.kind},
|
||||
${row.state},
|
||||
${row.title},
|
||||
${row.detail},
|
||||
${row.spawnedByActivityId},
|
||||
${row.providerRefs ? JSON.stringify(row.providerRefs) : null},
|
||||
${row.startedAt},
|
||||
${row.updatedAt},
|
||||
${row.completedAt}
|
||||
)
|
||||
ON CONFLICT (work_unit_id)
|
||||
DO UPDATE SET
|
||||
thread_id = excluded.thread_id,
|
||||
turn_id = excluded.turn_id,
|
||||
parent_work_unit_id = excluded.parent_work_unit_id,
|
||||
kind = excluded.kind,
|
||||
state = excluded.state,
|
||||
title = excluded.title,
|
||||
detail = excluded.detail,
|
||||
spawned_by_activity_id = excluded.spawned_by_activity_id,
|
||||
provider_refs_json = excluded.provider_refs_json,
|
||||
started_at = excluded.started_at,
|
||||
updated_at = excluded.updated_at,
|
||||
completed_at = excluded.completed_at
|
||||
`,
|
||||
});
|
||||
|
||||
const listProjectionThreadWorkUnitRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadWorkUnitsInput,
|
||||
Result: ProjectionThreadWorkUnitDbRowSchema,
|
||||
execute: ({ threadId }) => sql`
|
||||
SELECT
|
||||
work_unit_id AS "workUnitId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
parent_work_unit_id AS "parentWorkUnitId",
|
||||
kind,
|
||||
state,
|
||||
title,
|
||||
detail,
|
||||
spawned_by_activity_id AS "spawnedByActivityId",
|
||||
provider_refs_json AS "providerRefs",
|
||||
started_at AS "startedAt",
|
||||
updated_at AS "updatedAt",
|
||||
completed_at AS "completedAt"
|
||||
FROM projection_thread_work_units
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY started_at ASC, work_unit_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteProjectionThreadWorkUnitRows = SqlSchema.void({
|
||||
Request: DeleteProjectionThreadWorkUnitsInput,
|
||||
execute: ({ threadId }) => sql`
|
||||
DELETE FROM projection_thread_work_units
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
const upsert: ProjectionThreadWorkUnitRepositoryShape["upsert"] = (row) =>
|
||||
upsertProjectionThreadWorkUnitRow(row).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadWorkUnitRepository.upsert:query")),
|
||||
);
|
||||
|
||||
const listByThreadId: ProjectionThreadWorkUnitRepositoryShape["listByThreadId"] = (input) =>
|
||||
listProjectionThreadWorkUnitRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionThreadWorkUnitRepository.listByThreadId:query",
|
||||
"ProjectionThreadWorkUnitRepository.listByThreadId:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.map((rows) =>
|
||||
rows.map((row) => ({
|
||||
workUnitId: row.workUnitId,
|
||||
threadId: row.threadId,
|
||||
turnId: row.turnId,
|
||||
parentWorkUnitId: row.parentWorkUnitId,
|
||||
kind: row.kind,
|
||||
state: row.state,
|
||||
title: row.title,
|
||||
detail: row.detail,
|
||||
spawnedByActivityId: row.spawnedByActivityId,
|
||||
...(row.providerRefs !== null ? { providerRefs: row.providerRefs } : {}),
|
||||
startedAt: row.startedAt,
|
||||
updatedAt: row.updatedAt,
|
||||
completedAt: row.completedAt,
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteByThreadId: ProjectionThreadWorkUnitRepositoryShape["deleteByThreadId"] = (input) =>
|
||||
deleteProjectionThreadWorkUnitRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadWorkUnitRepository.deleteByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
listByThreadId,
|
||||
deleteByThreadId,
|
||||
} satisfies ProjectionThreadWorkUnitRepositoryShape;
|
||||
});
|
||||
|
||||
export const ProjectionThreadWorkUnitRepositoryLive = Layer.effect(
|
||||
ProjectionThreadWorkUnitRepository,
|
||||
makeProjectionThreadWorkUnitRepository,
|
||||
);
|
||||
@@ -47,6 +47,8 @@ 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,
|
||||
@@ -61,6 +63,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.pendingMessageId},
|
||||
${row.sourceProposedPlanThreadId},
|
||||
${row.sourceProposedPlanId},
|
||||
${row.assistantMessageId},
|
||||
${row.state},
|
||||
${row.requestedAt},
|
||||
@@ -74,6 +78,8 @@ 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,
|
||||
@@ -106,6 +112,8 @@ 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,
|
||||
@@ -120,6 +128,8 @@ const makeProjectionTurnRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
NULL,
|
||||
${row.messageId},
|
||||
${row.sourceProposedPlanThreadId},
|
||||
${row.sourceProposedPlanId},
|
||||
NULL,
|
||||
'pending',
|
||||
${row.requestedAt},
|
||||
@@ -141,6 +151,8 @@ 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}
|
||||
@@ -162,6 +174,8 @@ 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",
|
||||
@@ -193,6 +207,8 @@ 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,6 +25,9 @@ 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 Migration0016 from "./Migrations/016_ProjectionThreadWorkUnits.ts";
|
||||
import { Effect } from "effect";
|
||||
|
||||
/**
|
||||
@@ -51,6 +54,9 @@ const loader = Migrator.fromRecord({
|
||||
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
|
||||
"12_ProjectionThreadsInteractionMode": Migration0012,
|
||||
"13_ProjectionThreadProposedPlans": Migration0013,
|
||||
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
|
||||
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
|
||||
"16_ProjectionThreadWorkUnits": Migration0016,
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
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
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
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
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
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_activities
|
||||
ADD COLUMN work_unit_id TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE TABLE IF NOT EXISTS projection_thread_work_units (
|
||||
work_unit_id TEXT PRIMARY KEY,
|
||||
thread_id TEXT NOT NULL,
|
||||
turn_id TEXT NOT NULL,
|
||||
parent_work_unit_id TEXT,
|
||||
kind TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
detail TEXT,
|
||||
spawned_by_activity_id TEXT,
|
||||
provider_refs_json TEXT,
|
||||
started_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
completed_at TEXT
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_work_units_thread_turn
|
||||
ON projection_thread_work_units(thread_id, turn_id, started_at)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_work_units_thread_parent
|
||||
ON projection_thread_work_units(thread_id, parent_work_unit_id, started_at)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_work_units (
|
||||
work_unit_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
parent_work_unit_id,
|
||||
kind,
|
||||
state,
|
||||
title,
|
||||
detail,
|
||||
spawned_by_activity_id,
|
||||
provider_refs_json,
|
||||
started_at,
|
||||
updated_at,
|
||||
completed_at
|
||||
)
|
||||
SELECT
|
||||
'wu:' || thread_id || ':turn:' || turn_id || ':root',
|
||||
thread_id,
|
||||
turn_id,
|
||||
NULL,
|
||||
'primary_agent',
|
||||
CASE state
|
||||
WHEN 'completed' THEN 'completed'
|
||||
WHEN 'error' THEN 'failed'
|
||||
WHEN 'interrupted' THEN 'stopped'
|
||||
ELSE 'running'
|
||||
END,
|
||||
'Primary agent',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
COALESCE(started_at, requested_at),
|
||||
COALESCE(completed_at, started_at, requested_at),
|
||||
CASE
|
||||
WHEN state IN ('completed', 'error', 'interrupted') THEN COALESCE(completed_at, started_at, requested_at)
|
||||
ELSE NULL
|
||||
END
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NOT NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_thread_activities
|
||||
SET work_unit_id = 'wu:' || thread_id || ':turn:' || turn_id || ':root'
|
||||
WHERE turn_id IS NOT NULL
|
||||
AND work_unit_id IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
OrchestrationThreadActivityTone,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WorkUnitId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
@@ -23,6 +24,7 @@ export const ProjectionThreadActivity = Schema.Struct({
|
||||
activityId: EventId,
|
||||
threadId: ThreadId,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
workUnitId: Schema.NullOr(WorkUnitId),
|
||||
tone: OrchestrationThreadActivityTone,
|
||||
kind: Schema.String,
|
||||
summary: Schema.String,
|
||||
|
||||
@@ -15,6 +15,8 @@ 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,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
OrchestrationWorkUnitKind,
|
||||
OrchestrationWorkUnitProviderRefs,
|
||||
OrchestrationWorkUnitState,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
TrimmedNonEmptyString,
|
||||
WorkUnitId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../Errors.ts";
|
||||
|
||||
export const ProjectionThreadWorkUnit = Schema.Struct({
|
||||
workUnitId: WorkUnitId,
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
parentWorkUnitId: Schema.NullOr(WorkUnitId),
|
||||
kind: OrchestrationWorkUnitKind,
|
||||
state: OrchestrationWorkUnitState,
|
||||
title: TrimmedNonEmptyString,
|
||||
detail: Schema.NullOr(TrimmedNonEmptyString),
|
||||
spawnedByActivityId: Schema.NullOr(EventId),
|
||||
providerRefs: Schema.optional(OrchestrationWorkUnitProviderRefs),
|
||||
startedAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
completedAt: Schema.NullOr(IsoDateTime),
|
||||
});
|
||||
export type ProjectionThreadWorkUnit = typeof ProjectionThreadWorkUnit.Type;
|
||||
|
||||
export const ListProjectionThreadWorkUnitsInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type ListProjectionThreadWorkUnitsInput = typeof ListProjectionThreadWorkUnitsInput.Type;
|
||||
|
||||
export const DeleteProjectionThreadWorkUnitsInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type DeleteProjectionThreadWorkUnitsInput = typeof DeleteProjectionThreadWorkUnitsInput.Type;
|
||||
|
||||
export interface ProjectionThreadWorkUnitRepositoryShape {
|
||||
readonly upsert: (
|
||||
workUnit: ProjectionThreadWorkUnit,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
readonly listByThreadId: (
|
||||
input: ListProjectionThreadWorkUnitsInput,
|
||||
) => Effect.Effect<ReadonlyArray<ProjectionThreadWorkUnit>, ProjectionRepositoryError>;
|
||||
readonly deleteByThreadId: (
|
||||
input: DeleteProjectionThreadWorkUnitsInput,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
export class ProjectionThreadWorkUnitRepository extends ServiceMap.Service<
|
||||
ProjectionThreadWorkUnitRepository,
|
||||
ProjectionThreadWorkUnitRepositoryShape
|
||||
>()("t3/persistence/Services/ProjectionThreadWorkUnits/ProjectionThreadWorkUnitRepository") {}
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationCheckpointStatus,
|
||||
ThreadId,
|
||||
@@ -34,6 +35,8 @@ 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,
|
||||
@@ -50,6 +53,8 @@ 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,
|
||||
@@ -65,6 +70,8 @@ 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;
|
||||
|
||||
@@ -258,6 +258,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
@@ -274,13 +275,162 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("maps ultrathink to max effort and prefixes the prompt", () => {
|
||||
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* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.deepEqual(createInput?.options.settings, {
|
||||
fastMode: true,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("ignores claude fast mode for non-opus 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: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.settings, undefined);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("treats ultrathink as a prompt keyword instead of a session effort", () => {
|
||||
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: {
|
||||
@@ -293,6 +443,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
threadId: session.threadId,
|
||||
input: "Investigate the edge cases",
|
||||
attachments: [],
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "ultrathink",
|
||||
@@ -301,7 +452,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, "max");
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
const promptText = yield* Effect.promise(() => readFirstPromptText(createInput));
|
||||
assert.equal(promptText, "Ultrathink:\nInvestigate the edge cases");
|
||||
}).pipe(
|
||||
@@ -739,6 +890,65 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("treats user-aborted Claude results as interrupted without a runtime error", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "error_during_execution",
|
||||
is_error: false,
|
||||
errors: ["Error: Request was aborted."],
|
||||
stop_reason: "tool_use",
|
||||
session_id: "sdk-session-abort",
|
||||
uuid: "result-abort",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
assert.deepEqual(
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
|
||||
const turnCompleted = runtimeEvents[runtimeEvents.length - 1];
|
||||
assert.equal(turnCompleted?.type, "turn.completed");
|
||||
if (turnCompleted?.type === "turn.completed") {
|
||||
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
|
||||
assert.equal(turnCompleted.payload.state, "interrupted");
|
||||
assert.equal(turnCompleted.payload.errorMessage, "Error: Request was aborted.");
|
||||
assert.equal(turnCompleted.payload.stopReason, "tool_use");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("forwards Claude task progress summaries for subagent updates", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
@@ -786,6 +996,84 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("attaches Claude subagent task progress to the collab tool item", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 8).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "delegate this",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "stream_event",
|
||||
session_id: "sdk-session-task-item-link",
|
||||
uuid: "stream-task-item-link",
|
||||
parent_tool_use_id: null,
|
||||
event: {
|
||||
type: "content_block_start",
|
||||
index: 0,
|
||||
content_block: {
|
||||
type: "tool_use",
|
||||
id: "tool-task-link-1",
|
||||
name: "Task",
|
||||
input: {
|
||||
description: "Review the database layer",
|
||||
},
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "tool_progress",
|
||||
session_id: "sdk-session-task-item-link",
|
||||
uuid: "tool-progress-task-link",
|
||||
parent_tool_use_id: null,
|
||||
tool_use_id: "tool-task-link-1",
|
||||
tool_name: "Task",
|
||||
task_id: "task-subagent-link-1",
|
||||
elapsed_time_seconds: 1,
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "task_progress",
|
||||
task_id: "task-subagent-link-1",
|
||||
description: "Running background teammate",
|
||||
summary: "Code reviewer checked the migration edge cases.",
|
||||
session_id: "sdk-session-task-item-link",
|
||||
uuid: "task-progress-task-link",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const progressEvent = runtimeEvents.find(
|
||||
(event) =>
|
||||
event.type === "task.progress" && event.payload.taskId === "task-subagent-link-1",
|
||||
);
|
||||
assert.equal(progressEvent?.type, "task.progress");
|
||||
if (progressEvent?.type === "task.progress") {
|
||||
assert.equal(progressEvent.itemId, "tool-task-link-1");
|
||||
assert.equal(progressEvent.providerRefs?.providerItemId, "tool-task-link-1");
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"emits completion only after turn result when assistant frames arrive before deltas",
|
||||
() => {
|
||||
@@ -1690,6 +1978,143 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("captures ExitPlanMode as a proposed plan and denies auto-exit", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "plan this",
|
||||
interactionMode: "plan",
|
||||
attachments: [],
|
||||
});
|
||||
yield* Stream.take(adapter.streamEvents, 1).pipe(Stream.runDrain);
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
const canUseTool = createInput?.options.canUseTool;
|
||||
assert.equal(typeof canUseTool, "function");
|
||||
if (!canUseTool) {
|
||||
return;
|
||||
}
|
||||
|
||||
const permissionPromise = canUseTool(
|
||||
"ExitPlanMode",
|
||||
{
|
||||
plan: "# Ship it\n\n- one\n- two",
|
||||
allowedPrompts: [{ tool: "Bash", prompt: "run tests" }],
|
||||
},
|
||||
{
|
||||
signal: new AbortController().signal,
|
||||
toolUseID: "tool-exit-1",
|
||||
},
|
||||
);
|
||||
|
||||
const proposedEvent = yield* Stream.runHead(adapter.streamEvents);
|
||||
assert.equal(proposedEvent._tag, "Some");
|
||||
if (proposedEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(proposedEvent.value.type, "turn.proposed.completed");
|
||||
if (proposedEvent.value.type !== "turn.proposed.completed") {
|
||||
return;
|
||||
}
|
||||
assert.equal(proposedEvent.value.payload.planMarkdown, "# Ship it\n\n- one\n- two");
|
||||
assert.deepEqual(proposedEvent.value.providerRefs, {
|
||||
providerItemId: ProviderItemId.makeUnsafe("tool-exit-1"),
|
||||
});
|
||||
|
||||
const permissionResult = yield* Effect.promise(() => permissionPromise);
|
||||
assert.equal((permissionResult as PermissionResult).behavior, "deny");
|
||||
const deniedResult = permissionResult as PermissionResult & {
|
||||
message?: string;
|
||||
};
|
||||
assert.equal(deniedResult.message?.includes("captured your proposed plan"), true);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("extracts proposed plans from assistant ExitPlanMode snapshots", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* Stream.take(adapter.streamEvents, 3).pipe(Stream.runDrain);
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "plan this",
|
||||
interactionMode: "plan",
|
||||
attachments: [],
|
||||
});
|
||||
yield* Stream.take(adapter.streamEvents, 1).pipe(Stream.runDrain);
|
||||
|
||||
const proposedEventFiber = yield* Stream.filter(
|
||||
adapter.streamEvents,
|
||||
(event) => event.type === "turn.proposed.completed",
|
||||
).pipe(Stream.runHead, Effect.forkChild);
|
||||
|
||||
harness.query.emit({
|
||||
type: "assistant",
|
||||
session_id: "sdk-session-exit-plan",
|
||||
uuid: "assistant-exit-plan",
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
model: "claude-opus-4-6",
|
||||
id: "msg-exit-plan",
|
||||
type: "message",
|
||||
role: "assistant",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "tool-exit-2",
|
||||
name: "ExitPlanMode",
|
||||
input: {
|
||||
plan: "# Final plan\n\n- capture it",
|
||||
},
|
||||
},
|
||||
],
|
||||
stop_reason: null,
|
||||
stop_sequence: null,
|
||||
usage: {},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const proposedEvent = yield* Fiber.join(proposedEventFiber);
|
||||
assert.equal(proposedEvent._tag, "Some");
|
||||
if (proposedEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(proposedEvent.value.type, "turn.proposed.completed");
|
||||
if (proposedEvent.value.type !== "turn.proposed.completed") {
|
||||
return;
|
||||
}
|
||||
assert.equal(proposedEvent.value.payload.planMarkdown, "# Final plan\n\n- capture it");
|
||||
assert.deepEqual(proposedEvent.value.providerRefs, {
|
||||
providerItemId: ProviderItemId.makeUnsafe("tool-exit-2"),
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("handles AskUserQuestion via user-input.requested/resolved lifecycle", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -37,7 +37,15 @@ import {
|
||||
TurnId,
|
||||
type UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
import { applyClaudePromptEffortPrefix, getEffectiveClaudeCodeEffort } from "@t3tools/shared/model";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getEffectiveClaudeCodeEffort,
|
||||
getReasoningEffortOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
} from "@t3tools/shared/model";
|
||||
import { Cause, DateTime, Deferred, Effect, Layer, Queue, Random, Ref, Stream } from "effect";
|
||||
|
||||
import {
|
||||
@@ -80,6 +88,8 @@ interface ClaudeTurnState {
|
||||
readonly items: Array<unknown>;
|
||||
readonly assistantTextBlocks: Map<number, AssistantTextBlockState>;
|
||||
readonly assistantTextBlockOrder: Array<number>;
|
||||
readonly capturedProposedPlanKeys: Set<string>;
|
||||
readonly taskItemIds: Map<string, string>;
|
||||
nextSyntheticAssistantBlockIndex: number;
|
||||
}
|
||||
|
||||
@@ -166,6 +176,27 @@ function toMessage(cause: unknown, fallback: string): string {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function resultErrorsText(result: SDKResultMessage): string {
|
||||
return "errors" in result && Array.isArray(result.errors)
|
||||
? result.errors.join(" ").toLowerCase()
|
||||
: "";
|
||||
}
|
||||
|
||||
function isInterruptedResult(result: SDKResultMessage): boolean {
|
||||
const errors = resultErrorsText(result);
|
||||
if (errors.includes("interrupt")) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return (
|
||||
result.subtype === "error_during_execution" &&
|
||||
result.is_error === false &&
|
||||
(errors.includes("request was aborted") ||
|
||||
errors.includes("interrupted by user") ||
|
||||
errors.includes("aborted"))
|
||||
);
|
||||
}
|
||||
|
||||
function asRuntimeItemId(value: string): RuntimeItemId {
|
||||
return RuntimeItemId.makeUnsafe(value);
|
||||
}
|
||||
@@ -347,10 +378,18 @@ function buildUserMessage(input: ProviderSendTurnInput): SDKUserMessage {
|
||||
}
|
||||
}
|
||||
|
||||
const text = applyClaudePromptEffortPrefix(
|
||||
fragments.join("\n\n"),
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
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",
|
||||
@@ -368,8 +407,8 @@ function turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStat
|
||||
return "completed";
|
||||
}
|
||||
|
||||
const errors = result.errors.join(" ").toLowerCase();
|
||||
if (errors.includes("interrupt")) {
|
||||
const errors = resultErrorsText(result);
|
||||
if (isInterruptedResult(result)) {
|
||||
return "interrupted";
|
||||
}
|
||||
if (errors.includes("cancel")) {
|
||||
@@ -396,6 +435,20 @@ function nativeProviderRefs(
|
||||
return {};
|
||||
}
|
||||
|
||||
function taskEventParentItemFields(
|
||||
context: ClaudeSessionContext,
|
||||
taskId: string,
|
||||
): Pick<ProviderRuntimeEvent, "itemId" | "providerRefs"> | undefined {
|
||||
const providerItemId = context.turnState?.taskItemIds.get(taskId);
|
||||
if (!providerItemId) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
itemId: asRuntimeItemId(providerItemId),
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId }),
|
||||
};
|
||||
}
|
||||
|
||||
function extractAssistantTextBlocks(message: SDKMessage): Array<string> {
|
||||
if (message.type !== "assistant") {
|
||||
return [];
|
||||
@@ -458,6 +511,28 @@ function extractTextContent(value: unknown): string {
|
||||
return extractTextContent(record.content);
|
||||
}
|
||||
|
||||
function extractExitPlanModePlan(value: unknown): string | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const record = value as {
|
||||
plan?: unknown;
|
||||
};
|
||||
return typeof record.plan === "string" && record.plan.trim().length > 0
|
||||
? record.plan.trim()
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function exitPlanCaptureKey(input: {
|
||||
readonly toolUseId?: string | undefined;
|
||||
readonly planMarkdown: string;
|
||||
}): string {
|
||||
return input.toolUseId && input.toolUseId.length > 0
|
||||
? `tool:${input.toolUseId}`
|
||||
: `plan:${input.planMarkdown}`;
|
||||
}
|
||||
|
||||
function tryParseJsonRecord(value: string): Record<string, unknown> | undefined {
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
@@ -1037,6 +1112,54 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
});
|
||||
});
|
||||
|
||||
const emitProposedPlanCompleted = (
|
||||
context: ClaudeSessionContext,
|
||||
input: {
|
||||
readonly planMarkdown: string;
|
||||
readonly toolUseId?: string | undefined;
|
||||
readonly rawSource: "claude.sdk.message" | "claude.sdk.permission";
|
||||
readonly rawMethod: string;
|
||||
readonly rawPayload: unknown;
|
||||
},
|
||||
): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
const turnState = context.turnState;
|
||||
const planMarkdown = input.planMarkdown.trim();
|
||||
if (!turnState || planMarkdown.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const captureKey = exitPlanCaptureKey({
|
||||
toolUseId: input.toolUseId,
|
||||
planMarkdown,
|
||||
});
|
||||
if (turnState.capturedProposedPlanKeys.has(captureKey)) {
|
||||
return;
|
||||
}
|
||||
turnState.capturedProposedPlanKeys.add(captureKey);
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.proposed.completed",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId: turnState.turnId,
|
||||
payload: {
|
||||
planMarkdown,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
providerItemId: input.toolUseId,
|
||||
}),
|
||||
raw: {
|
||||
source: input.rawSource,
|
||||
method: input.rawMethod,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const completeTurn = (
|
||||
context: ClaudeSessionContext,
|
||||
status: ProviderRuntimeTurnStatus,
|
||||
@@ -1490,6 +1613,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
items: [],
|
||||
assistantTextBlocks: new Map(),
|
||||
assistantTextBlockOrder: [],
|
||||
capturedProposedPlanKeys: new Set(),
|
||||
taskItemIds: new Map(),
|
||||
nextSyntheticAssistantBlockIndex: -1,
|
||||
};
|
||||
context.session = {
|
||||
@@ -1519,6 +1644,35 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
});
|
||||
}
|
||||
|
||||
const content = message.message?.content;
|
||||
if (Array.isArray(content)) {
|
||||
for (const block of content) {
|
||||
if (!block || typeof block !== "object") {
|
||||
continue;
|
||||
}
|
||||
const toolUse = block as {
|
||||
type?: unknown;
|
||||
id?: unknown;
|
||||
name?: unknown;
|
||||
input?: unknown;
|
||||
};
|
||||
if (toolUse.type !== "tool_use" || toolUse.name !== "ExitPlanMode") {
|
||||
continue;
|
||||
}
|
||||
const planMarkdown = extractExitPlanModePlan(toolUse.input);
|
||||
if (!planMarkdown) {
|
||||
continue;
|
||||
}
|
||||
yield* emitProposedPlanCompleted(context, {
|
||||
planMarkdown,
|
||||
toolUseId: typeof toolUse.id === "string" ? toolUse.id : undefined,
|
||||
rawSource: "claude.sdk.message",
|
||||
rawMethod: "claude/assistant",
|
||||
rawPayload: message,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (context.turnState) {
|
||||
context.turnState.items.push(message.message);
|
||||
yield* backfillAssistantTextBlocksFromSnapshot(context, message);
|
||||
@@ -1643,6 +1797,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
case "task_started":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
...taskEventParentItemFields(context, message.task_id),
|
||||
type: "task.started",
|
||||
payload: {
|
||||
taskId: RuntimeTaskId.makeUnsafe(message.task_id),
|
||||
@@ -1654,6 +1809,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
case "task_progress":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
...taskEventParentItemFields(context, message.task_id),
|
||||
type: "task.progress",
|
||||
payload: {
|
||||
taskId: RuntimeTaskId.makeUnsafe(message.task_id),
|
||||
@@ -1667,6 +1823,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
case "task_notification":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
...taskEventParentItemFields(context, message.task_id),
|
||||
type: "task.completed",
|
||||
payload: {
|
||||
taskId: RuntimeTaskId.makeUnsafe(message.task_id),
|
||||
@@ -1730,8 +1887,13 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
};
|
||||
|
||||
if (message.type === "tool_progress") {
|
||||
if (message.task_id && context.turnState) {
|
||||
context.turnState.taskItemIds.set(message.task_id, message.tool_use_id);
|
||||
}
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
itemId: asRuntimeItemId(message.tool_use_id),
|
||||
providerRefs: nativeProviderRefs(context, { providerItemId: message.tool_use_id }),
|
||||
type: "tool.progress",
|
||||
payload: {
|
||||
toolUseId: message.tool_use_id,
|
||||
@@ -2074,6 +2236,28 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
return yield* handleAskUserQuestion(context, toolInput, callbackOptions);
|
||||
}
|
||||
|
||||
if (toolName === "ExitPlanMode") {
|
||||
const planMarkdown = extractExitPlanModePlan(toolInput);
|
||||
if (planMarkdown) {
|
||||
yield* emitProposedPlanCompleted(context, {
|
||||
planMarkdown,
|
||||
toolUseId: callbackOptions.toolUseID,
|
||||
rawSource: "claude.sdk.permission",
|
||||
rawMethod: "canUseTool/ExitPlanMode",
|
||||
rawPayload: {
|
||||
toolName,
|
||||
input: toolInput,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
behavior: "deny",
|
||||
message:
|
||||
"The client captured your proposed plan. Stop here and wait for the user's feedback or implementation request in a later turn.",
|
||||
} satisfies PermissionResult;
|
||||
}
|
||||
|
||||
const runtimeMode = input.runtimeMode ?? "full-access";
|
||||
if (runtimeMode === "full-access") {
|
||||
return {
|
||||
@@ -2193,11 +2377,30 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
);
|
||||
|
||||
const providerOptions = input.providerOptions?.claudeAgent;
|
||||
const effort = input.modelOptions?.claudeAgent?.effort;
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
input.modelOptions?.claudeAgent?.effort ?? null,
|
||||
);
|
||||
const supportedEffortOptions = getReasoningEffortOptions("claudeAgent", input.model);
|
||||
const effort =
|
||||
requestedEffort && supportedEffortOptions.includes(requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
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 } : {}),
|
||||
@@ -2213,6 +2416,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
...(providerOptions?.maxThinkingTokens !== undefined
|
||||
? { maxThinkingTokens: providerOptions.maxThinkingTokens }
|
||||
: {}),
|
||||
...(Object.keys(settings).length > 0 ? { settings } : {}),
|
||||
...(resumeState?.resume ? { resume: resumeState.resume } : {}),
|
||||
...(resumeState?.resumeSessionAt ? { resumeSessionAt: resumeState.resumeSessionAt } : {}),
|
||||
includePartialMessages: true,
|
||||
@@ -2302,6 +2506,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
...(providerOptions?.maxThinkingTokens !== undefined
|
||||
? { maxThinkingTokens: providerOptions.maxThinkingTokens }
|
||||
: {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
},
|
||||
},
|
||||
providerRefs: {},
|
||||
@@ -2368,6 +2573,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
items: [],
|
||||
assistantTextBlocks: new Map(),
|
||||
assistantTextBlockOrder: [],
|
||||
capturedProposedPlanKeys: new Set(),
|
||||
taskItemIds: new Map(),
|
||||
nextSyntheticAssistantBlockIndex: -1,
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { PassThrough } from "node:stream";
|
||||
import { query, type SpawnOptions, type SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
async function* emptyPrompt(): AsyncGenerator<never, void, void> {}
|
||||
|
||||
class FakeClaudeCodeProcess implements SpawnedProcess {
|
||||
readonly stdin = new PassThrough();
|
||||
readonly stdout = new PassThrough();
|
||||
killed = false;
|
||||
exitCode: number | null = null;
|
||||
|
||||
private readonly events = new EventEmitter();
|
||||
private bufferedInput = "";
|
||||
|
||||
constructor(
|
||||
private readonly onMessage: (
|
||||
message: Record<string, unknown>,
|
||||
process: FakeClaudeCodeProcess,
|
||||
) => void,
|
||||
) {
|
||||
this.stdin.setEncoding("utf8");
|
||||
this.stdin.on("data", (chunk: string) => {
|
||||
this.bufferedInput += chunk;
|
||||
this.drainInput();
|
||||
});
|
||||
}
|
||||
|
||||
emitJson(message: unknown): void {
|
||||
this.stdout.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
|
||||
kill(_signal: NodeJS.Signals): boolean {
|
||||
this.killed = true;
|
||||
this.exitCode = 0;
|
||||
this.stdout.end();
|
||||
this.events.emit("exit", 0, null);
|
||||
return true;
|
||||
}
|
||||
|
||||
on(
|
||||
event: "exit" | "error",
|
||||
listener:
|
||||
| ((code: number | null, signal: NodeJS.Signals | null) => void)
|
||||
| ((error: Error) => void),
|
||||
): void {
|
||||
this.events.on(event, listener);
|
||||
}
|
||||
|
||||
once(
|
||||
event: "exit" | "error",
|
||||
listener:
|
||||
| ((code: number | null, signal: NodeJS.Signals | null) => void)
|
||||
| ((error: Error) => void),
|
||||
): void {
|
||||
this.events.once(event, listener);
|
||||
}
|
||||
|
||||
off(
|
||||
event: "exit" | "error",
|
||||
listener:
|
||||
| ((code: number | null, signal: NodeJS.Signals | null) => void)
|
||||
| ((error: Error) => void),
|
||||
): void {
|
||||
this.events.off(event, listener);
|
||||
}
|
||||
|
||||
private drainInput(): void {
|
||||
while (true) {
|
||||
const newlineIndex = this.bufferedInput.indexOf("\n");
|
||||
if (newlineIndex === -1) {
|
||||
return;
|
||||
}
|
||||
const line = this.bufferedInput.slice(0, newlineIndex).trim();
|
||||
this.bufferedInput = this.bufferedInput.slice(newlineIndex + 1);
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
this.onMessage(JSON.parse(line) as Record<string, unknown>, this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("Claude SDK fast mode probe", () => {
|
||||
let activeQuery: ReturnType<typeof query> | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
activeQuery?.close();
|
||||
activeQuery = null;
|
||||
});
|
||||
|
||||
it("passes fast mode through the SDK settings flag", async () => {
|
||||
let spawnOptions: SpawnOptions | undefined;
|
||||
|
||||
activeQuery = query({
|
||||
prompt: emptyPrompt(),
|
||||
options: {
|
||||
persistSession: false,
|
||||
settings: {
|
||||
fastMode: true,
|
||||
},
|
||||
spawnClaudeCodeProcess: (options): SpawnedProcess => {
|
||||
spawnOptions = options;
|
||||
return new FakeClaudeCodeProcess((message, process) => {
|
||||
if (
|
||||
message.type !== "control_request" ||
|
||||
typeof message.request_id !== "string" ||
|
||||
!message.request ||
|
||||
typeof message.request !== "object" ||
|
||||
(message.request as { subtype?: unknown }).subtype !== "initialize"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.emitJson({
|
||||
type: "control_response",
|
||||
response: {
|
||||
subtype: "success",
|
||||
request_id: message.request_id,
|
||||
response: {
|
||||
commands: [],
|
||||
agents: [],
|
||||
output_style: "default",
|
||||
available_output_styles: ["default"],
|
||||
models: [],
|
||||
account: {
|
||||
subscriptionType: "max",
|
||||
},
|
||||
fast_mode_state: "on",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const initialization = await activeQuery.initializationResult();
|
||||
expect(initialization.fast_mode_state).toBe("on");
|
||||
|
||||
expect(spawnOptions).toBeDefined();
|
||||
const settingsFlagIndex = spawnOptions?.args.indexOf("--settings") ?? -1;
|
||||
expect(settingsFlagIndex).toBeGreaterThan(-1);
|
||||
expect(JSON.parse(spawnOptions?.args[settingsFlagIndex + 1] ?? "")).toEqual({
|
||||
fastMode: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -800,6 +800,48 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prefers manager-assigned turn ids for Codex task events", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-codex-task-started-parent-turn"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-parent"),
|
||||
itemId: asItemId("call-collab-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "codex/event/task_started",
|
||||
payload: {
|
||||
id: "turn-child",
|
||||
msg: {
|
||||
type: "task_started",
|
||||
turn_id: "turn-child",
|
||||
collaboration_mode_kind: "default",
|
||||
},
|
||||
conversationId: "child-provider-thread",
|
||||
},
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
assert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.type, "task.started");
|
||||
if (firstEvent.value.type !== "task.started") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.turnId, "turn-parent");
|
||||
assert.equal(firstEvent.value.itemId, "call-collab-1");
|
||||
assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent");
|
||||
assert.equal(firstEvent.value.providerRefs?.providerItemId, "call-collab-1");
|
||||
assert.equal(firstEvent.value.payload.taskId, "turn-child");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
|
||||
@@ -109,6 +109,14 @@ function asNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||
return value?.trim() ? TurnId.makeUnsafe(value) : undefined;
|
||||
}
|
||||
|
||||
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
|
||||
return value?.trim() ? ProviderItemId.makeUnsafe(value) : undefined;
|
||||
}
|
||||
|
||||
function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" {
|
||||
switch (value) {
|
||||
case "completed":
|
||||
@@ -415,27 +423,27 @@ function codexEventBase(
|
||||
): Omit<ProviderRuntimeEvent, "type" | "payload"> {
|
||||
const payload = asObject(event.payload);
|
||||
const msg = codexEventMessage(payload);
|
||||
const turnId = asString(msg?.turn_id) ?? asString(msg?.turnId);
|
||||
const itemId = asString(msg?.item_id) ?? asString(msg?.itemId);
|
||||
const turnId = event.turnId ?? toTurnId(asString(msg?.turn_id) ?? asString(msg?.turnId));
|
||||
const itemId = event.itemId ?? toProviderItemId(asString(msg?.item_id) ?? asString(msg?.itemId));
|
||||
const requestId = asString(msg?.request_id) ?? asString(msg?.requestId);
|
||||
const base = runtimeEventBase(event, canonicalThreadId);
|
||||
const providerRefs = base.providerRefs
|
||||
? {
|
||||
...base.providerRefs,
|
||||
...(turnId ? { providerTurnId: turnId } : {}),
|
||||
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
|
||||
...(itemId ? { providerItemId: itemId } : {}),
|
||||
...(requestId ? { providerRequestId: requestId } : {}),
|
||||
}
|
||||
: {
|
||||
...(turnId ? { providerTurnId: turnId } : {}),
|
||||
...(itemId ? { providerItemId: ProviderItemId.makeUnsafe(itemId) } : {}),
|
||||
...(itemId ? { providerItemId: itemId } : {}),
|
||||
...(requestId ? { providerRequestId: requestId } : {}),
|
||||
};
|
||||
|
||||
return {
|
||||
...base,
|
||||
...(turnId ? { turnId: TurnId.makeUnsafe(turnId) } : {}),
|
||||
...(itemId ? { itemId: asRuntimeItemId(ProviderItemId.makeUnsafe(itemId)) } : {}),
|
||||
...(turnId ? { turnId } : {}),
|
||||
...(itemId ? { itemId: asRuntimeItemId(itemId) } : {}),
|
||||
...(requestId ? { requestId: asRuntimeRequestId(requestId) } : {}),
|
||||
...(Object.keys(providerRefs).length > 0 ? { providerRefs } : {}),
|
||||
};
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = '2.12.9'
|
||||
const PACKAGE_VERSION = '2.12.10'
|
||||
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||
const activeClientIds = new Set()
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Schema } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AppSettingsSchema,
|
||||
DEFAULT_TIMESTAMP_FORMAT,
|
||||
getAppModelOptions,
|
||||
normalizeCustomModelSlugs,
|
||||
@@ -35,6 +37,7 @@ 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",
|
||||
@@ -86,3 +89,27 @@ describe("provider-specific custom models", () => {
|
||||
expect(claudeOptions.some((option) => option.slug === "claude/custom-opus")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("AppSettingsSchema", () => {
|
||||
it("fills decoding defaults for persisted settings that predate newer keys", () => {
|
||||
const decode = Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema));
|
||||
|
||||
expect(
|
||||
decode(
|
||||
JSON.stringify({
|
||||
codexBinaryPath: "/usr/local/bin/codex",
|
||||
confirmThreadDelete: false,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
codexBinaryPath: "/usr/local/bin/codex",
|
||||
codexHomePath: "",
|
||||
defaultThreadEnvMode: "local",
|
||||
confirmThreadDelete: false,
|
||||
enableAssistantStreaming: false,
|
||||
timestampFormat: DEFAULT_TIMESTAMP_FORMAT,
|
||||
customCodexModels: [],
|
||||
customClaudeModels: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
+29
-26
@@ -1,43 +1,46 @@
|
||||
import { useCallback } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { TrimmedNonEmptyString, type ProviderKind } from "@t3tools/contracts";
|
||||
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { useLocalStorage } from "./hooks/useLocalStorage";
|
||||
import { EnvMode } from "./components/BranchToolbar.logic";
|
||||
|
||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
export const TIMESTAMP_FORMAT_OPTIONS = ["locale", "12-hour", "24-hour"] as const;
|
||||
export type TimestampFormat = (typeof TIMESTAMP_FORMAT_OPTIONS)[number];
|
||||
|
||||
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
|
||||
export type TimestampFormat = typeof TimestampFormat.Type;
|
||||
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
|
||||
|
||||
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
|
||||
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
|
||||
claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
|
||||
};
|
||||
|
||||
const AppSettingsSchema = Schema.Struct({
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some("")),
|
||||
),
|
||||
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some("")),
|
||||
),
|
||||
defaultThreadEnvMode: Schema.Literals(["local", "worktree"]).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some("local")),
|
||||
),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(false)),
|
||||
),
|
||||
timestampFormat: Schema.Literals(["locale", "12-hour", "24-hour"]).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(DEFAULT_TIMESTAMP_FORMAT)),
|
||||
),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
customClaudeModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
const withDefaults =
|
||||
<
|
||||
S extends Schema.Top & Schema.WithoutConstructorDefault,
|
||||
D extends S["~type.make.in"] & S["Encoded"],
|
||||
>(
|
||||
fallback: () => D,
|
||||
) =>
|
||||
(schema: S) =>
|
||||
schema.pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(fallback())),
|
||||
Schema.withDecodingDefault(() => fallback()),
|
||||
);
|
||||
|
||||
export const AppSettingsSchema = Schema.Struct({
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
||||
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
||||
defaultThreadEnvMode: EnvMode.pipe(withDefaults(() => "local" as const satisfies EnvMode)),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
|
||||
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
|
||||
customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
|
||||
textGenerationModel: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||
export interface AppModelOption {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { Schema } from "effect";
|
||||
|
||||
export type EnvMode = "local" | "worktree";
|
||||
export const EnvMode = Schema.Literals(["local", "worktree"]);
|
||||
export type EnvMode = typeof EnvMode.Type;
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
activeWorktreePath: string | null;
|
||||
|
||||
@@ -21,6 +21,10 @@ 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";
|
||||
@@ -150,6 +154,25 @@ 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;
|
||||
@@ -221,6 +244,7 @@ function createSnapshotForTargetUser(options: {
|
||||
messages,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
@@ -275,6 +299,7 @@ function addThreadToSnapshot(
|
||||
messages: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
session: {
|
||||
threadId,
|
||||
@@ -345,6 +370,8 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
id: "plan-browser-test",
|
||||
turnId: null,
|
||||
planMarkdown,
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: isoAt(1_000),
|
||||
updatedAt: isoAt(1_001),
|
||||
},
|
||||
@@ -531,6 +558,13 @@ 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> {
|
||||
@@ -1011,6 +1045,166 @@ 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,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
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,6 +4,11 @@ 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";
|
||||
@@ -125,3 +130,44 @@ 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,34 +2,37 @@ 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,
|
||||
RuntimeMode,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getDefaultModel,
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptions,
|
||||
normalizeCodexModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveReasoningEffortForProvider,
|
||||
resolveModelSlugForProvider,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
} from "@t3tools/shared/model";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
@@ -56,8 +59,10 @@ import {
|
||||
deriveTimelineEntries,
|
||||
deriveActiveWorkStartedAt,
|
||||
deriveActivePlanState,
|
||||
findSidebarProposedPlan,
|
||||
findLatestProposedPlan,
|
||||
deriveWorkLogEntries,
|
||||
hasActionableProposedPlan,
|
||||
hasToolActivityForTurn,
|
||||
isLatestTurnSettled,
|
||||
formatElapsed,
|
||||
@@ -130,6 +135,14 @@ 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";
|
||||
@@ -140,7 +153,8 @@ 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 { ProviderTraitsPicker } from "./chat/CodexTraitsPicker";
|
||||
import { ClaudeTraitsMenuContent, ClaudeTraitsPicker } from "./chat/ClaudeTraitsPicker";
|
||||
import { CodexTraitsMenuContent, CodexTraitsPicker } from "./chat/CodexTraitsPicker";
|
||||
import { CompactComposerControlsMenu } from "./chat/CompactComposerControlsMenu";
|
||||
import { ComposerPendingApprovalPanel } from "./chat/ComposerPendingApprovalPanel";
|
||||
import { ComposerPendingUserInputPanel } from "./chat/ComposerPendingUserInputPanel";
|
||||
@@ -148,10 +162,12 @@ 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,
|
||||
@@ -176,13 +192,13 @@ const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnsw
|
||||
|
||||
function formatOutgoingPrompt(params: {
|
||||
provider: ProviderKind;
|
||||
effort: ProviderReasoningEffort | null;
|
||||
effort: string | null;
|
||||
text: string;
|
||||
}): string {
|
||||
if (params.provider !== "claudeAgent") {
|
||||
return params.text;
|
||||
if (params.provider === "claudeAgent" && params.effort === "ultrathink") {
|
||||
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeCodeEffort | null);
|
||||
}
|
||||
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeCodeEffort | null);
|
||||
return params.text;
|
||||
}
|
||||
const COMPOSER_PATH_QUERY_DEBOUNCE_MS = 120;
|
||||
const SCRIPT_TERMINAL_COLS = 120;
|
||||
@@ -199,6 +215,23 @@ 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;
|
||||
}
|
||||
@@ -223,6 +256,16 @@ 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);
|
||||
@@ -231,11 +274,21 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setComposerDraftInteractionMode = useComposerDraftStore(
|
||||
(store) => store.setInteractionMode,
|
||||
);
|
||||
const setComposerDraftEffort = useComposerDraftStore((store) => store.setEffort);
|
||||
const setComposerDraftCodexFastMode = useComposerDraftStore((store) => store.setCodexFastMode);
|
||||
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,
|
||||
);
|
||||
@@ -262,6 +315,7 @@ 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>
|
||||
>({});
|
||||
@@ -284,7 +338,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 new thread" to carry the sidebar-open intent across navigation.
|
||||
// Used by "Implement in a 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);
|
||||
@@ -364,12 +418,40 @@ 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);
|
||||
@@ -533,47 +615,53 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
draftModel,
|
||||
) as ModelSlug;
|
||||
}, [baseThreadModel, composerDraft.model, customModelsForSelectedProvider, selectedProvider]);
|
||||
const reasoningOptions = getReasoningEffortOptions(selectedProvider);
|
||||
const supportsReasoningEffort = reasoningOptions.length > 0;
|
||||
const draftModelOptions = composerDraft.modelOptions;
|
||||
const selectedCodexEffort =
|
||||
selectedProvider === "codex"
|
||||
? (resolveReasoningEffortForProvider("codex", composerDraft.effort) ??
|
||||
? (resolveReasoningEffortForProvider("codex", draftModelOptions?.codex?.reasoningEffort) ??
|
||||
getDefaultReasoningEffort("codex"))
|
||||
: null;
|
||||
const selectedClaudeEffort =
|
||||
const selectedClaudeReasoningOptions =
|
||||
selectedProvider === "claudeAgent"
|
||||
? (resolveReasoningEffortForProvider("claudeAgent", composerDraft.effort) ??
|
||||
getDefaultReasoningEffort("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;
|
||||
})()
|
||||
: null;
|
||||
const selectedEffort = selectedCodexEffort ?? selectedClaudeEffort;
|
||||
const selectedCodexFastModeEnabled =
|
||||
selectedProvider === "codex" ? composerDraft.codexFastMode : false;
|
||||
const isClaudeUltrathink = selectedClaudeEffort === "ultrathink";
|
||||
const isClaudeUltrathink =
|
||||
selectedProvider === "claudeAgent" &&
|
||||
supportsClaudeUltrathinkKeyword(selectedModel) &&
|
||||
isClaudeUltrathinkPrompt(prompt);
|
||||
const selectedPromptEffort = selectedCodexEffort ?? selectedClaudeBaseEffort;
|
||||
const selectedModelOptionsForDispatch = useMemo(() => {
|
||||
if (selectedProvider === "codex") {
|
||||
const codexOptions = {
|
||||
...(supportsReasoningEffort && selectedCodexEffort
|
||||
? { reasoningEffort: selectedCodexEffort }
|
||||
: {}),
|
||||
...(selectedCodexFastModeEnabled ? { fastMode: true } : {}),
|
||||
};
|
||||
return Object.keys(codexOptions).length > 0 ? { codex: codexOptions } : undefined;
|
||||
const codexOptions = normalizeCodexModelOptions(draftModelOptions?.codex);
|
||||
return codexOptions ? { codex: codexOptions } : undefined;
|
||||
}
|
||||
if (selectedProvider === "claudeAgent" && selectedClaudeEffort) {
|
||||
return {
|
||||
claudeAgent: {
|
||||
effort: selectedClaudeEffort,
|
||||
},
|
||||
};
|
||||
if (selectedProvider === "claudeAgent") {
|
||||
const claudeOptions = normalizeClaudeModelOptions(
|
||||
selectedModel,
|
||||
draftModelOptions?.claudeAgent,
|
||||
);
|
||||
return claudeOptions ? { claudeAgent: claudeOptions } : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}, [
|
||||
selectedClaudeEffort,
|
||||
selectedCodexEffort,
|
||||
selectedCodexFastModeEnabled,
|
||||
selectedProvider,
|
||||
supportsReasoningEffort,
|
||||
]);
|
||||
}, [draftModelOptions, selectedModel, selectedProvider]);
|
||||
const providerOptionsForDispatch = useMemo(() => {
|
||||
if (!settings.codexBinaryPath && !settings.codexHomePath) {
|
||||
return undefined;
|
||||
@@ -682,6 +770,16 @@ 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],
|
||||
@@ -690,7 +788,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
pendingUserInputs.length === 0 &&
|
||||
interactionMode === "plan" &&
|
||||
latestTurnSettled &&
|
||||
activeProposedPlan !== null;
|
||||
hasActionableProposedPlan(activeProposedPlan);
|
||||
const activePendingApproval = pendingApprovals[0] ?? null;
|
||||
const isComposerApprovalState = activePendingApproval !== null;
|
||||
const hasComposerHeader =
|
||||
@@ -1140,6 +1238,48 @@ 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;
|
||||
@@ -1480,7 +1620,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const togglePlanSidebar = useCallback(() => {
|
||||
setPlanSidebarOpen((open) => {
|
||||
if (open) {
|
||||
const turnKey = activePlan?.turnId ?? activeProposedPlan?.turnId ?? null;
|
||||
const turnKey = activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? null;
|
||||
if (turnKey) {
|
||||
planSidebarDismissedForTurnRef.current = turnKey;
|
||||
}
|
||||
@@ -1489,7 +1629,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
return !open;
|
||||
});
|
||||
}, [activePlan?.turnId, activeProposedPlan?.turnId]);
|
||||
}, [activePlan?.turnId, sidebarProposedPlan?.turnId]);
|
||||
|
||||
const persistThreadSettingsForNextTurn = useCallback(
|
||||
async (input: {
|
||||
@@ -1777,6 +1917,10 @@ 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) {
|
||||
@@ -2251,7 +2395,17 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onAdvanceActivePendingUserInput();
|
||||
return;
|
||||
}
|
||||
const trimmed = prompt.trim();
|
||||
const promptForSend = promptRef.current;
|
||||
const {
|
||||
trimmedPrompt: trimmed,
|
||||
sendableTerminalContexts: sendableComposerTerminalContexts,
|
||||
expiredTerminalContextCount,
|
||||
hasSendableContent,
|
||||
} = deriveComposerSendState({
|
||||
prompt: promptForSend,
|
||||
imageCount: composerImages.length,
|
||||
terminalContexts: composerTerminalContexts,
|
||||
});
|
||||
if (showPlanFollowUpPrompt && activeProposedPlan) {
|
||||
const followUp = resolvePlanFollowUpSubmission({
|
||||
draftText: trimmed,
|
||||
@@ -2269,9 +2423,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
const standaloneSlashCommand =
|
||||
composerImages.length === 0 ? parseStandaloneComposerSlashCommand(trimmed) : null;
|
||||
composerImages.length === 0 && sendableComposerTerminalContexts.length === 0
|
||||
? parseStandaloneComposerSlashCommand(trimmed)
|
||||
: null;
|
||||
if (standaloneSlashCommand) {
|
||||
await handleInteractionModeChange(standaloneSlashCommand);
|
||||
handleInteractionModeChange(standaloneSlashCommand);
|
||||
promptRef.current = "";
|
||||
clearComposerDraftContent(activeThread.id);
|
||||
setComposerHighlightedItemId(null);
|
||||
@@ -2279,7 +2435,20 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setComposerTrigger(null);
|
||||
return;
|
||||
}
|
||||
if (!trimmed && composerImages.length === 0) return;
|
||||
if (!hasSendableContent) {
|
||||
if (expiredTerminalContextCount > 0) {
|
||||
const toastCopy = buildExpiredTerminalContextToastCopy(
|
||||
expiredTerminalContextCount,
|
||||
"empty",
|
||||
);
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: toastCopy.title,
|
||||
description: toastCopy.description,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!activeProject) return;
|
||||
const threadIdForSend = activeThread.id;
|
||||
const isFirstMessage = !isServerThread || activeThread.messages.length === 0;
|
||||
@@ -2304,12 +2473,17 @@ 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: selectedEffort,
|
||||
text: trimmed || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
effort: selectedPromptEffort,
|
||||
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
});
|
||||
const turnAttachmentsPromise = Promise.all(
|
||||
composerImagesSnapshot.map(async (image) => ({
|
||||
@@ -2344,6 +2518,17 @@ 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);
|
||||
@@ -2391,6 +2576,8 @@ 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";
|
||||
}
|
||||
@@ -2499,7 +2686,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
if (
|
||||
!turnStartSucceeded &&
|
||||
promptRef.current.length === 0 &&
|
||||
composerImagesRef.current.length === 0
|
||||
composerImagesRef.current.length === 0 &&
|
||||
composerTerminalContextsRef.current.length === 0
|
||||
) {
|
||||
setOptimisticUserMessages((existing) => {
|
||||
const removed = existing.filter((message) => message.id === messageIdForSend);
|
||||
@@ -2509,11 +2697,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const next = existing.filter((message) => message.id !== messageIdForSend);
|
||||
return next.length === existing.length ? existing : next;
|
||||
});
|
||||
promptRef.current = trimmed;
|
||||
setPrompt(trimmed);
|
||||
setComposerCursor(collapseExpandedComposerCursor(trimmed, trimmed.length));
|
||||
promptRef.current = promptForSend;
|
||||
setPrompt(promptForSend);
|
||||
setComposerCursor(collapseExpandedComposerCursor(promptForSend, promptForSend.length));
|
||||
addComposerImagesToDraft(composerImagesSnapshot.map(cloneComposerImageForRetry));
|
||||
setComposerTrigger(detectComposerTrigger(trimmed, trimmed.length));
|
||||
addComposerTerminalContextsToDraft(composerTerminalContextsSnapshot);
|
||||
setComposerTrigger(detectComposerTrigger(promptForSend, promptForSend.length));
|
||||
}
|
||||
setThreadError(
|
||||
threadIdForSend,
|
||||
@@ -2714,7 +2903,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
const outgoingMessageText = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
effort: selectedEffort,
|
||||
effort: selectedPromptEffort,
|
||||
text: trimmed,
|
||||
});
|
||||
|
||||
@@ -2766,6 +2955,14 @@ 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).
|
||||
@@ -2790,6 +2987,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
activeProposedPlan,
|
||||
beginSendPhase,
|
||||
forceStickToBottom,
|
||||
isConnecting,
|
||||
@@ -2798,7 +2996,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
persistThreadSettingsForNextTurn,
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedEffort,
|
||||
selectedPromptEffort,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
providerOptionsForDispatch,
|
||||
@@ -2830,7 +3028,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const implementationPrompt = buildPlanImplementationPrompt(planMarkdown);
|
||||
const outgoingImplementationPrompt = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
effort: selectedEffort,
|
||||
effort: selectedPromptEffort,
|
||||
text: implementationPrompt,
|
||||
});
|
||||
const nextThreadTitle = truncateTitle(buildPlanImplementationThreadTitle(planMarkdown));
|
||||
@@ -2927,7 +3125,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
navigate,
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedEffort,
|
||||
selectedPromptEffort,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
providerOptionsForDispatch,
|
||||
@@ -2959,19 +3157,21 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
setComposerDraftProvider,
|
||||
],
|
||||
);
|
||||
const onEffortSelect = useCallback(
|
||||
(effort: ProviderReasoningEffort) => {
|
||||
setComposerDraftEffort(threadId, effort);
|
||||
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));
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[scheduleComposerFocus, setComposerDraftEffort, threadId],
|
||||
);
|
||||
const onCodexFastModeChange = useCallback(
|
||||
(enabled: boolean) => {
|
||||
setComposerDraftCodexFastMode(threadId, enabled);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[scheduleComposerFocus, setComposerDraftCodexFastMode, threadId],
|
||||
[scheduleComposerFocus, setPrompt],
|
||||
);
|
||||
const onEnvModeChange = useCallback(
|
||||
(mode: DraftThreadEnvMode) => {
|
||||
@@ -3033,6 +3233,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
terminalContextIds: string[];
|
||||
} => {
|
||||
const editorSnapshot = composerEditorRef.current?.readSnapshot();
|
||||
if (editorSnapshot) {
|
||||
@@ -3042,8 +3243,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
value: promptRef.current,
|
||||
cursor: composerCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(promptRef.current, composerCursor),
|
||||
terminalContextIds: composerTerminalContexts.map((context) => context.id),
|
||||
};
|
||||
}, [composerCursor]);
|
||||
}, [composerCursor, composerTerminalContexts]);
|
||||
|
||||
const resolveActiveComposerTrigger = useCallback((): {
|
||||
snapshot: { value: string; cursor: number; expandedCursor: number };
|
||||
@@ -3159,6 +3361,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
nextCursor: number,
|
||||
expandedCursor: number,
|
||||
cursorAdjacentToMention: boolean,
|
||||
terminalContextIds: string[],
|
||||
) => {
|
||||
if (activePendingProgress?.activeQuestion && activePendingUserInput) {
|
||||
onChangeActivePendingUserInputCustomAnswer(
|
||||
@@ -3172,6 +3375,12 @@ 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),
|
||||
@@ -3180,8 +3389,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
[
|
||||
activePendingProgress?.activeQuestion,
|
||||
activePendingUserInput,
|
||||
composerTerminalContexts,
|
||||
onChangeActivePendingUserInputCustomAnswer,
|
||||
setPrompt,
|
||||
setComposerDraftTerminalContexts,
|
||||
threadId,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -3434,8 +3646,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{/* Textarea area */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative px-3 pb-2 sm:px-4",
|
||||
@@ -3535,6 +3745,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
: prompt
|
||||
}
|
||||
cursor={composerCursor}
|
||||
terminalContexts={
|
||||
!isComposerApprovalState && pendingUserInputs.length === 0
|
||||
? composerTerminalContexts
|
||||
: []
|
||||
}
|
||||
onRemoveTerminalContext={removeComposerTerminalContextFromDraft}
|
||||
onChange={onPromptChange}
|
||||
onCommandKeyDown={onComposerCommandKey}
|
||||
onPaste={onComposerPaste}
|
||||
@@ -3597,40 +3813,46 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{isComposerFooterCompact ? (
|
||||
<CompactComposerControlsMenu
|
||||
activePlan={Boolean(
|
||||
activePlan || activeProposedPlan || planSidebarOpen,
|
||||
activePlan || sidebarProposedPlan || planSidebarOpen,
|
||||
)}
|
||||
interactionMode={interactionMode}
|
||||
planSidebarOpen={planSidebarOpen}
|
||||
runtimeMode={runtimeMode}
|
||||
selectedEffort={selectedEffort}
|
||||
selectedProvider={selectedProvider}
|
||||
selectedCodexFastModeEnabled={selectedCodexFastModeEnabled}
|
||||
reasoningOptions={reasoningOptions}
|
||||
onEffortSelect={onEffortSelect}
|
||||
onCodexFastModeChange={onCodexFastModeChange}
|
||||
traitsMenuContent={
|
||||
selectedProvider === "codex" ? (
|
||||
<CodexTraitsMenuContent threadId={threadId} />
|
||||
) : selectedProvider === "claudeAgent" ? (
|
||||
<ClaudeTraitsMenuContent
|
||||
threadId={threadId}
|
||||
model={selectedModel}
|
||||
onPromptChange={setPromptFromTraits}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
onToggleInteractionMode={toggleInteractionMode}
|
||||
onTogglePlanSidebar={togglePlanSidebar}
|
||||
onToggleRuntimeMode={toggleRuntimeMode}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{selectedEffort != null ? (
|
||||
{selectedProvider === "codex" ? (
|
||||
<>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="mx-0.5 hidden h-4 sm:block"
|
||||
/>
|
||||
<ProviderTraitsPicker
|
||||
provider={selectedProvider}
|
||||
effort={selectedEffort}
|
||||
options={reasoningOptions}
|
||||
onEffortChange={onEffortSelect}
|
||||
{...(selectedProvider === "codex"
|
||||
? {
|
||||
fastModeEnabled: selectedCodexFastModeEnabled,
|
||||
onFastModeChange: onCodexFastModeChange,
|
||||
}
|
||||
: {})}
|
||||
<CodexTraitsPicker threadId={threadId} />
|
||||
</>
|
||||
) : selectedProvider === "claudeAgent" ? (
|
||||
<>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
className="mx-0.5 hidden h-4 sm:block"
|
||||
/>
|
||||
<ClaudeTraitsPicker
|
||||
threadId={threadId}
|
||||
model={selectedModel}
|
||||
onPromptChange={setPromptFromTraits}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
@@ -3687,7 +3909,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</span>
|
||||
</Button>
|
||||
|
||||
{activePlan || activeProposedPlan || planSidebarOpen ? (
|
||||
{activePlan || sidebarProposedPlan || planSidebarOpen ? (
|
||||
<>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
@@ -3815,7 +4037,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
disabled={isSendBusy || isConnecting}
|
||||
onClick={() => void onImplementPlanInNewThread()}
|
||||
>
|
||||
Implement in new thread
|
||||
Implement in a new thread
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
@@ -3826,9 +4048,7 @@ 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 ||
|
||||
(!prompt.trim() && composerImages.length === 0)
|
||||
isSendBusy || isConnecting || !composerSendState.hasSendableContent
|
||||
}
|
||||
aria-label={
|
||||
isConnecting
|
||||
@@ -3919,14 +4139,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
{planSidebarOpen ? (
|
||||
<PlanSidebar
|
||||
activePlan={activePlan}
|
||||
activeProposedPlan={activeProposedPlan}
|
||||
activeProposedPlan={sidebarProposedPlan}
|
||||
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 ?? activeProposedPlan?.turnId ?? null;
|
||||
const turnKey = activePlan?.turnId ?? sidebarProposedPlan?.turnId ?? null;
|
||||
if (turnKey) {
|
||||
planSidebarDismissedForTurnRef.current = turnKey;
|
||||
}
|
||||
@@ -3960,6 +4180,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onActiveTerminalChange={activateTerminal}
|
||||
onCloseTerminal={closeTerminal}
|
||||
onHeightChange={setTerminalHeight}
|
||||
onAddTerminalContext={addTerminalContextToDraft}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
|
||||
@@ -26,8 +26,10 @@ import {
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
KEY_BACKSPACE_COMMAND,
|
||||
$getRoot,
|
||||
DecoratorNode,
|
||||
type ElementNode,
|
||||
type LexicalNode,
|
||||
type SerializedLexicalNode,
|
||||
TextNode,
|
||||
type EditorConfig,
|
||||
type EditorState,
|
||||
@@ -36,14 +38,17 @@ import {
|
||||
type Spread,
|
||||
} from "lexical";
|
||||
import {
|
||||
createContext,
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ClipboardEventHandler,
|
||||
type ReactElement,
|
||||
type Ref,
|
||||
} from "react";
|
||||
|
||||
@@ -51,11 +56,21 @@ import {
|
||||
clampCollapsedComposerCursor,
|
||||
collapseExpandedComposerCursor,
|
||||
expandCollapsedComposerCursor,
|
||||
isCollapsedCursorAdjacentToMention,
|
||||
isCollapsedCursorAdjacentToInlineToken,
|
||||
} 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 } from "~/vscode-icons";
|
||||
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";
|
||||
|
||||
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
|
||||
|
||||
@@ -68,6 +83,21 @@ 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;
|
||||
|
||||
@@ -100,8 +130,7 @@ class ComposerMentionNode extends TextNode {
|
||||
|
||||
override createDOM(_config: EditorConfig): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
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.className = COMPOSER_INLINE_CHIP_CLASS_NAME;
|
||||
dom.contentEditable = "false";
|
||||
dom.setAttribute("spellcheck", "false");
|
||||
renderMentionChipDom(dom, this.__path);
|
||||
@@ -141,15 +170,76 @@ function $createComposerMentionNode(path: string): ComposerMentionNode {
|
||||
return $applyNodeReplacement(new ComposerMentionNode(path));
|
||||
}
|
||||
|
||||
function inferMentionPathKind(pathValue: string): "file" | "directory" {
|
||||
const base = basenameOfPath(pathValue);
|
||||
if (base.startsWith(".") && !base.slice(1).includes(".")) {
|
||||
return "directory";
|
||||
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";
|
||||
}
|
||||
if (base.includes(".")) {
|
||||
return "file";
|
||||
|
||||
static override clone(node: ComposerTerminalContextNode): ComposerTerminalContextNode {
|
||||
return new ComposerTerminalContextNode(node.__context, node.__key);
|
||||
}
|
||||
return "directory";
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
function resolvedThemeFromDocument(): "light" | "dark" {
|
||||
@@ -165,25 +255,91 @@ function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
|
||||
const icon = document.createElement("img");
|
||||
icon.alt = "";
|
||||
icon.ariaHidden = "true";
|
||||
icon.className = "size-3.5 shrink-0 opacity-85";
|
||||
icon.className = COMPOSER_INLINE_CHIP_ICON_CLASS_NAME;
|
||||
icon.loading = "lazy";
|
||||
icon.src = getVscodeIconUrlForEntry(pathValue, inferMentionPathKind(pathValue), theme);
|
||||
icon.src = getVscodeIconUrlForEntry(pathValue, inferEntryKindFromPath(pathValue), theme);
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.className = "truncate select-none leading-tight";
|
||||
label.className = COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME;
|
||||
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 (node instanceof ComposerMentionNode) {
|
||||
return 1;
|
||||
if (isComposerInlineTokenNode(node)) {
|
||||
return getComposerInlineTokenTextLength(node);
|
||||
}
|
||||
if ($isTextNode(node)) {
|
||||
return node.getTextContentSize();
|
||||
@@ -198,6 +354,9 @@ function getComposerNodeTextLength(node: LexicalNode): number {
|
||||
}
|
||||
|
||||
function getComposerNodeExpandedTextLength(node: LexicalNode): number {
|
||||
if (isComposerInlineTokenNode(node)) {
|
||||
return getComposerInlineTokenExpandedTextLength(node);
|
||||
}
|
||||
if ($isTextNode(node)) {
|
||||
return node.getTextContentSize();
|
||||
}
|
||||
@@ -233,10 +392,13 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return offset + (pointOffset > 0 ? 1 : 0);
|
||||
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
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);
|
||||
@@ -277,10 +439,13 @@ function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: numbe
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return offset + (pointOffset > 0 ? node.getTextContentSize() : 0);
|
||||
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
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);
|
||||
@@ -305,25 +470,10 @@ function findSelectionPointAtOffset(
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "text" | "element" } | null {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
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;
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
}
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
@@ -438,40 +588,67 @@ function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function $setComposerEditorPrompt(prompt: string): void {
|
||||
function $setComposerEditorPrompt(
|
||||
prompt: string,
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>,
|
||||
): void {
|
||||
const root = $getRoot();
|
||||
root.clear();
|
||||
const paragraph = $createParagraphNode();
|
||||
root.append(paragraph);
|
||||
|
||||
const segments = splitPromptIntoComposerSegments(prompt);
|
||||
const segments = splitPromptIntoComposerSegments(prompt, terminalContexts);
|
||||
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 };
|
||||
readSnapshot: () => {
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
terminalContextIds: string[];
|
||||
};
|
||||
}
|
||||
|
||||
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",
|
||||
@@ -540,7 +717,7 @@ function ComposerCommandKeyPlugin(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionArrowPlugin() {
|
||||
function ComposerInlineTokenArrowPlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -554,7 +731,7 @@ function ComposerMentionArrowPlugin() {
|
||||
const currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
if (currentOffset <= 0) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "left")) {
|
||||
if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "left")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset - 1;
|
||||
@@ -581,7 +758,7 @@ function ComposerMentionArrowPlugin() {
|
||||
const composerLength = $getComposerRootLength();
|
||||
if (currentOffset >= composerLength) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "right")) {
|
||||
if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "right")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset + 1;
|
||||
@@ -606,7 +783,7 @@ function ComposerMentionArrowPlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionSelectionNormalizePlugin() {
|
||||
function ComposerInlineTokenSelectionNormalizePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -616,7 +793,7 @@ function ComposerMentionSelectionNormalizePlugin() {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
if (!(anchorNode instanceof ComposerMentionNode)) return;
|
||||
if (!isComposerInlineTokenNode(anchorNode)) return;
|
||||
if (selection.anchor.offset === 0) return;
|
||||
const beforeOffset = getAbsoluteOffsetForPoint(anchorNode, 0);
|
||||
afterOffset = beforeOffset + 1;
|
||||
@@ -634,8 +811,9 @@ function ComposerMentionSelectionNormalizePlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionBackspacePlugin() {
|
||||
function ComposerInlineTokenBackspacePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const { onRemoveTerminalContext } = useContext(ComposerTerminalContextActionsContext);
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerCommand(
|
||||
@@ -647,18 +825,23 @@ function ComposerMentionBackspacePlugin() {
|
||||
}
|
||||
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
const removeMentionNode = (candidate: unknown): boolean => {
|
||||
if (!(candidate instanceof ComposerMentionNode)) {
|
||||
const selectionOffset = $readSelectionOffsetFromEditorState(0);
|
||||
const removeInlineTokenNode = (candidate: unknown): boolean => {
|
||||
if (!isComposerInlineTokenNode(candidate)) {
|
||||
return false;
|
||||
}
|
||||
const mentionStart = getAbsoluteOffsetForPoint(candidate, 0);
|
||||
const tokenStart = getAbsoluteOffsetForPoint(candidate, 0);
|
||||
candidate.remove();
|
||||
$setSelectionAtComposerOffset(mentionStart);
|
||||
if (candidate instanceof ComposerTerminalContextNode) {
|
||||
onRemoveTerminalContext(candidate.__context.id);
|
||||
$setSelectionAtComposerOffset(selectionOffset);
|
||||
} else {
|
||||
$setSelectionAtComposerOffset(tokenStart);
|
||||
}
|
||||
event?.preventDefault();
|
||||
return true;
|
||||
};
|
||||
|
||||
if (removeMentionNode(anchorNode)) {
|
||||
if (removeInlineTokenNode(anchorNode)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -666,13 +849,13 @@ function ComposerMentionBackspacePlugin() {
|
||||
if (selection.anchor.offset > 0) {
|
||||
return false;
|
||||
}
|
||||
if (removeMentionNode(anchorNode.getPreviousSibling())) {
|
||||
if (removeInlineTokenNode(anchorNode.getPreviousSibling())) {
|
||||
return true;
|
||||
}
|
||||
const parent = anchorNode.getParent();
|
||||
if ($isElementNode(parent)) {
|
||||
const index = anchorNode.getIndexWithinParent();
|
||||
if (index > 0 && removeMentionNode(parent.getChildAtIndex(index - 1))) {
|
||||
if (index > 0 && removeInlineTokenNode(parent.getChildAtIndex(index - 1))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -681,7 +864,7 @@ function ComposerMentionBackspacePlugin() {
|
||||
|
||||
if ($isElementNode(anchorNode)) {
|
||||
const childIndex = selection.anchor.offset - 1;
|
||||
if (childIndex >= 0 && removeMentionNode(anchorNode.getChildAtIndex(childIndex))) {
|
||||
if (childIndex >= 0 && removeInlineTokenNode(anchorNode.getChildAtIndex(childIndex))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -690,7 +873,7 @@ function ComposerMentionBackspacePlugin() {
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
}, [editor]);
|
||||
}, [editor, onRemoveTerminalContext]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -698,9 +881,11 @@ function ComposerMentionBackspacePlugin() {
|
||||
function ComposerPromptEditorInner({
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onRemoveTerminalContext,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
@@ -709,12 +894,19 @@ 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;
|
||||
@@ -727,7 +919,12 @@ function ComposerPromptEditorInner({
|
||||
useLayoutEffect(() => {
|
||||
const normalizedCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
|
||||
const contextsChanged = terminalContextsSignatureRef.current !== terminalContextsSignature;
|
||||
if (
|
||||
previousSnapshot.value === value &&
|
||||
previousSnapshot.cursor === normalizedCursor &&
|
||||
!contextsChanged
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -735,28 +932,30 @@ 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 && !isFocused) {
|
||||
if (previousSnapshot.value === value && !contextsChanged && !isFocused) {
|
||||
return;
|
||||
}
|
||||
|
||||
isApplyingControlledUpdateRef.current = true;
|
||||
editor.update(() => {
|
||||
const valueChanged = previousSnapshot.value !== value;
|
||||
if (previousSnapshot.value !== value) {
|
||||
$setComposerEditorPrompt(value);
|
||||
const shouldRewriteEditorState = previousSnapshot.value !== value || contextsChanged;
|
||||
if (shouldRewriteEditorState) {
|
||||
$setComposerEditorPrompt(value, terminalContexts);
|
||||
}
|
||||
if (valueChanged || isFocused) {
|
||||
if (shouldRewriteEditorState || isFocused) {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
}
|
||||
});
|
||||
queueMicrotask(() => {
|
||||
isApplyingControlledUpdateRef.current = false;
|
||||
});
|
||||
}, [cursor, editor, value]);
|
||||
}, [cursor, editor, terminalContexts, terminalContextsSignature, value]);
|
||||
|
||||
const focusAt = useCallback(
|
||||
(nextCursor: number) => {
|
||||
@@ -771,12 +970,14 @@ 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],
|
||||
@@ -786,6 +987,7 @@ function ComposerPromptEditorInner({
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
terminalContextIds: string[];
|
||||
} => {
|
||||
let snapshot = snapshotRef.current;
|
||||
editor.getEditorState().read(() => {
|
||||
@@ -803,10 +1005,12 @@ function ComposerPromptEditorInner({
|
||||
nextValue,
|
||||
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
|
||||
);
|
||||
const terminalContextIds = collectTerminalContextIds($getRoot());
|
||||
snapshot = {
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
expandedCursor: nextExpandedCursor,
|
||||
terminalContextIds,
|
||||
};
|
||||
});
|
||||
snapshotRef.current = snapshot;
|
||||
@@ -849,11 +1053,14 @@ function ComposerPromptEditorInner({
|
||||
nextValue,
|
||||
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
|
||||
);
|
||||
const terminalContextIds = collectTerminalContextIds($getRoot());
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
if (
|
||||
previousSnapshot.value === nextValue &&
|
||||
previousSnapshot.cursor === nextCursor &&
|
||||
previousSnapshot.expandedCursor === nextExpandedCursor
|
||||
previousSnapshot.expandedCursor === nextExpandedCursor &&
|
||||
previousSnapshot.terminalContextIds.length === terminalContextIds.length &&
|
||||
previousSnapshot.terminalContextIds.every((id, index) => id === terminalContextIds[index])
|
||||
) {
|
||||
return;
|
||||
}
|
||||
@@ -864,43 +1071,54 @@ function ComposerPromptEditorInner({
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
expandedCursor: nextExpandedCursor,
|
||||
terminalContextIds,
|
||||
};
|
||||
const cursorAdjacentToMention =
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, cursorAdjacentToMention);
|
||||
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(
|
||||
nextValue,
|
||||
nextCursor,
|
||||
nextExpandedCursor,
|
||||
cursorAdjacentToMention,
|
||||
terminalContextIds,
|
||||
);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<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>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -908,17 +1126,29 @@ export const ComposerPromptEditor = forwardRef<
|
||||
ComposerPromptEditorHandle,
|
||||
ComposerPromptEditorProps
|
||||
>(function ComposerPromptEditor(
|
||||
{ value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
|
||||
{
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onRemoveTerminalContext,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const initialValueRef = useRef(value);
|
||||
const initialTerminalContextsRef = useRef(terminalContexts);
|
||||
const initialConfig = useMemo<InitialConfigType>(
|
||||
() => ({
|
||||
namespace: "t3tools-composer-editor",
|
||||
editable: true,
|
||||
nodes: [ComposerMentionNode],
|
||||
nodes: [ComposerMentionNode, ComposerTerminalContextNode],
|
||||
editorState: () => {
|
||||
$setComposerEditorPrompt(initialValueRef.current);
|
||||
$setComposerEditorPrompt(initialValueRef.current, initialTerminalContextsRef.current);
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
@@ -932,8 +1162,10 @@ export const ComposerPromptEditor = forwardRef<
|
||||
<ComposerPromptEditorInner
|
||||
value={value}
|
||||
cursor={cursor}
|
||||
terminalContexts={terminalContexts}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
onRemoveTerminalContext={onRemoveTerminalContext}
|
||||
onChange={onChange}
|
||||
onPaste={onPaste}
|
||||
editorRef={ref}
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
resolveQuickAction,
|
||||
summarizeGitResult,
|
||||
} from "./GitActionsControl.logic";
|
||||
import { useAppSettings } from "~/appSettings";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Checkbox } from "~/components/ui/checkbox";
|
||||
import {
|
||||
@@ -154,6 +155,7 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
|
||||
}
|
||||
|
||||
export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsControlProps) {
|
||||
const { settings } = useAppSettings();
|
||||
const threadToastData = useMemo(
|
||||
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
|
||||
[activeThreadId],
|
||||
@@ -191,7 +193,11 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const initMutation = useMutation(gitInitMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
const runImmediateGitActionMutation = useMutation(
|
||||
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
|
||||
gitRunStackedActionMutationOptions({
|
||||
cwd: gitCwd,
|
||||
queryClient,
|
||||
model: settings.textGenerationModel ?? null,
|
||||
}),
|
||||
);
|
||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
|
||||
@@ -98,6 +98,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {
|
||||
],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
|
||||
@@ -141,6 +141,8 @@ describe("resolveThreadStatusPill", () => {
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
planMarkdown: "# Plan",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
},
|
||||
],
|
||||
session: {
|
||||
@@ -155,6 +157,35 @@ 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,6 +1,10 @@
|
||||
import type { Thread } from "../types";
|
||||
import { cn } from "../lib/utils";
|
||||
import { findLatestProposedPlan, isLatestTurnSettled } from "../session-logic";
|
||||
import {
|
||||
findLatestProposedPlan,
|
||||
hasActionableProposedPlan,
|
||||
isLatestTurnSettled,
|
||||
} from "../session-logic";
|
||||
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
@@ -51,7 +55,7 @@ export function resolveThreadRowClassName(input: {
|
||||
isSelected: boolean;
|
||||
}): string {
|
||||
const baseClassName =
|
||||
"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";
|
||||
"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";
|
||||
|
||||
if (input.isSelected && input.isActive) {
|
||||
return cn(
|
||||
@@ -124,7 +128,9 @@ export function resolveThreadStatusPill(input: {
|
||||
!hasPendingUserInput &&
|
||||
thread.interactionMode === "plan" &&
|
||||
isLatestTurnSettled(thread.latestTurn, thread.session) &&
|
||||
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? null) !== null;
|
||||
hasActionableProposedPlan(
|
||||
findLatestProposedPlan(thread.proposedPlans, thread.latestTurn?.turnId ?? 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 { restrictToParentElement, restrictToVerticalAxis } from "@dnd-kit/modifiers";
|
||||
import { restrictToFirstScrollableAncestor, restrictToVerticalAxis } from "@dnd-kit/modifiers";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
@@ -561,7 +561,6 @@ 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
|
||||
@@ -665,7 +664,7 @@ export default function Sidebar() {
|
||||
],
|
||||
);
|
||||
|
||||
const { copyToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
|
||||
const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
|
||||
onCopy: (ctx) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
@@ -681,21 +680,40 @@ 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);
|
||||
@@ -708,8 +726,20 @@ 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") {
|
||||
copyToClipboard(threadId, { threadId });
|
||||
copyThreadIdToClipboard(threadId, { threadId });
|
||||
return;
|
||||
}
|
||||
if (clicked !== "delete") return;
|
||||
@@ -726,7 +756,15 @@ export default function Sidebar() {
|
||||
}
|
||||
await deleteThread(threadId);
|
||||
},
|
||||
[appSettings.confirmThreadDelete, copyToClipboard, deleteThread, markThreadUnread, threads],
|
||||
[
|
||||
appSettings.confirmThreadDelete,
|
||||
copyPathToClipboard,
|
||||
copyThreadIdToClipboard,
|
||||
deleteThread,
|
||||
markThreadUnread,
|
||||
projectCwdById,
|
||||
threads,
|
||||
],
|
||||
);
|
||||
|
||||
const handleMultiSelectContextMenu = useCallback(
|
||||
@@ -1282,7 +1320,7 @@ export default function Sidebar() {
|
||||
<DndContext
|
||||
sensors={projectDnDSensors}
|
||||
collisionDetection={projectCollisionDetection}
|
||||
modifiers={[restrictToVerticalAxis, restrictToParentElement]}
|
||||
modifiers={[restrictToVerticalAxis, restrictToFirstScrollableAncestor]}
|
||||
onDragStart={handleProjectDragStart}
|
||||
onDragEnd={handleProjectDragEnd}
|
||||
onDragCancel={handleProjectDragCancel}
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
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,6 +12,7 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { type TerminalContextSelection } from "~/lib/terminalContext";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import {
|
||||
extractTerminalLinks,
|
||||
@@ -29,6 +30,7 @@ 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;
|
||||
@@ -107,12 +109,85 @@ 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;
|
||||
@@ -122,9 +197,11 @@ interface TerminalViewportProps {
|
||||
function TerminalViewport({
|
||||
threadId,
|
||||
terminalId,
|
||||
terminalLabel,
|
||||
cwd,
|
||||
runtimeEnv,
|
||||
onSessionExited,
|
||||
onAddTerminalContext,
|
||||
focusRequestId,
|
||||
autoFocus,
|
||||
resizeEpoch,
|
||||
@@ -134,12 +211,27 @@ 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;
|
||||
@@ -165,6 +257,81 @@ 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;
|
||||
@@ -259,6 +426,38 @@ 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;
|
||||
@@ -310,11 +509,13 @@ 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);
|
||||
@@ -323,6 +524,7 @@ function TerminalViewport({
|
||||
}
|
||||
|
||||
if (event.type === "cleared") {
|
||||
clearSelectionAction();
|
||||
activeTerminal.clear();
|
||||
activeTerminal.write("\u001bc");
|
||||
return;
|
||||
@@ -383,7 +585,13 @@ 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;
|
||||
@@ -430,7 +638,9 @@ function TerminalViewport({
|
||||
window.cancelAnimationFrame(frame);
|
||||
};
|
||||
}, [drawerHeight, resizeEpoch, terminalId, threadId]);
|
||||
return <div ref={containerRef} className="h-full w-full overflow-hidden rounded-[4px]" />;
|
||||
return (
|
||||
<div ref={containerRef} className="relative h-full w-full overflow-hidden rounded-[4px]" />
|
||||
);
|
||||
}
|
||||
|
||||
interface ThreadTerminalDrawerProps {
|
||||
@@ -451,6 +661,7 @@ interface ThreadTerminalDrawerProps {
|
||||
onActiveTerminalChange: (terminalId: string) => void;
|
||||
onCloseTerminal: (terminalId: string) => void;
|
||||
onHeightChange: (height: number) => void;
|
||||
onAddTerminalContext: (selection: TerminalContextSelection) => void;
|
||||
}
|
||||
|
||||
interface TerminalActionButtonProps {
|
||||
@@ -500,6 +711,7 @@ export default function ThreadTerminalDrawer({
|
||||
onActiveTerminalChange,
|
||||
onCloseTerminal,
|
||||
onHeightChange,
|
||||
onAddTerminalContext,
|
||||
}: ThreadTerminalDrawerProps) {
|
||||
const [drawerHeight, setDrawerHeight] = useState(() => clampDrawerHeight(height));
|
||||
const [resizeEpoch, setResizeEpoch] = useState(0);
|
||||
@@ -796,9 +1008,11 @@ 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}
|
||||
@@ -814,9 +1028,11 @@ 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}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,257 @@
|
||||
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>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
import "../../index.css";
|
||||
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { CodexTraitsPicker } from "./CodexTraitsPicker";
|
||||
import { COMPOSER_DRAFT_STORAGE_KEY, useComposerDraftStore } from "../../composerDraftStore";
|
||||
|
||||
async function mountPicker(props: {
|
||||
reasoningEffort?: "low" | "medium" | "high" | "xhigh";
|
||||
fastModeEnabled: boolean;
|
||||
}) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-codex-traits");
|
||||
const draftsByThreadId = {} as ReturnType<
|
||||
typeof useComposerDraftStore.getState
|
||||
>["draftsByThreadId"];
|
||||
draftsByThreadId[threadId] = {
|
||||
prompt: "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
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 });
|
||||
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("CodexTraitsPicker", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows Fast in the trigger label when fast mode is active", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: true,
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("High · Fast");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).toContain("Extra High");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("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,7 +1,18 @@
|
||||
import { type ProviderKind, type ProviderReasoningEffort } from "@t3tools/contracts";
|
||||
import { getDefaultReasoningEffort } from "@t3tools/shared/model";
|
||||
import type {
|
||||
CodexModelOptions,
|
||||
CodexReasoningEffort,
|
||||
ProviderModelOptions,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
normalizeCodexModelOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
@@ -13,41 +24,99 @@ import {
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
|
||||
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;
|
||||
}
|
||||
const CODEX_REASONING_LABELS: Record<CodexReasoningEffort, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
xhigh: "Extra High",
|
||||
};
|
||||
|
||||
const claudeLabels: Record<string, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
max: "Max",
|
||||
ultrathink: "Ultrathink",
|
||||
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,
|
||||
};
|
||||
return claudeLabels[effort] ?? effort;
|
||||
}
|
||||
|
||||
export const ProviderTraitsPicker = memo(function ProviderTraitsPicker(props: {
|
||||
provider: ProviderKind;
|
||||
effort: ProviderReasoningEffort;
|
||||
fastModeEnabled?: boolean;
|
||||
options: ReadonlyArray<ProviderReasoningEffort>;
|
||||
onEffortChange: (effort: ProviderReasoningEffort) => void;
|
||||
onFastModeChange?: (enabled: boolean) => void;
|
||||
}) {
|
||||
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 }) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(props.provider);
|
||||
const triggerLabel = [
|
||||
effortLabel(props.provider, props.effort),
|
||||
...(props.provider === "codex" && props.fastModeEnabled ? ["Fast"] : []),
|
||||
]
|
||||
const modelOptions = useComposerThreadDraft(props.threadId).modelOptions?.codex;
|
||||
const { effort, fastModeEnabled } = getSelectedCodexTraits(modelOptions);
|
||||
const triggerLabel = [CODEX_REASONING_LABELS[effort], ...(fastModeEnabled ? ["Fast"] : [])]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
@@ -63,52 +132,17 @@ export const ProviderTraitsPicker = memo(function ProviderTraitsPicker(props: {
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
|
||||
className="min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:max-w-48 sm:px-3 [&_svg]:mx-0"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
|
||||
{triggerLabel}
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
<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.provider === "codex" && 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}
|
||||
<CodexTraitsMenuContent threadId={props.threadId} />
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
import { type ProviderModelOptions, ThreadId } from "@t3tools/contracts";
|
||||
import "../../index.css";
|
||||
|
||||
import { page } from "vitest/browser";
|
||||
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: {},
|
||||
});
|
||||
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}
|
||||
/>
|
||||
)
|
||||
}
|
||||
onToggleInteractionMode={vi.fn()}
|
||||
onTogglePlanSidebar={vi.fn()}
|
||||
onToggleRuntimeMode={vi.fn()}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("CompactComposerControlsMenu", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls for Opus", async () => {
|
||||
const mounted = await mountMenu();
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-Opus Claude models", async () => {
|
||||
const mounted = await mountMenu({ model: "claude-sonnet-4-6" });
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").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 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,16 +1,9 @@
|
||||
import {
|
||||
type ProviderKind,
|
||||
RuntimeMode,
|
||||
ProviderInteractionMode,
|
||||
type ProviderReasoningEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import { getDefaultReasoningEffort } from "@t3tools/shared/model";
|
||||
import { memo } from "react";
|
||||
import { ProviderInteractionMode, RuntimeMode } from "@t3tools/contracts";
|
||||
import { memo, type ReactNode } from "react";
|
||||
import { EllipsisIcon, ListTodoIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
@@ -24,26 +17,11 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
|
||||
interactionMode: ProviderInteractionMode;
|
||||
planSidebarOpen: boolean;
|
||||
runtimeMode: RuntimeMode;
|
||||
selectedEffort: ProviderReasoningEffort | null;
|
||||
selectedProvider: ProviderKind;
|
||||
selectedCodexFastModeEnabled: boolean;
|
||||
reasoningOptions: ReadonlyArray<ProviderReasoningEffort>;
|
||||
onEffortSelect: (effort: ProviderReasoningEffort) => void;
|
||||
onCodexFastModeChange: (enabled: boolean) => void;
|
||||
traitsMenuContent?: ReactNode;
|
||||
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
|
||||
@@ -59,80 +37,35 @@ export const CompactComposerControlsMenu = memo(function CompactComposerControls
|
||||
<EllipsisIcon aria-hidden="true" className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
{props.selectedEffort != null ? (
|
||||
{props.traitsMenuContent ? (
|
||||
<>
|
||||
<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.selectedProvider === "codex" ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
Fast Mode
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={props.selectedCodexFastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
props.onCodexFastModeChange(value === "on");
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
<MenuDivider />
|
||||
</>
|
||||
) : (
|
||||
<MenuDivider />
|
||||
)}
|
||||
{props.traitsMenuContent}
|
||||
<MenuDivider />
|
||||
</>
|
||||
) : null}
|
||||
<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>
|
||||
<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>
|
||||
<MenuDivider />
|
||||
<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>
|
||||
<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>
|
||||
{props.activePlan ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
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,5 +1,14 @@
|
||||
import { type MessageId, type TurnId } from "@t3tools/contracts";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import {
|
||||
measureElement as measureVirtualElement,
|
||||
type VirtualItem,
|
||||
@@ -33,9 +42,19 @@ 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;
|
||||
@@ -337,6 +356,8 @@ 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">
|
||||
@@ -378,14 +399,18 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{row.message.text && (
|
||||
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
|
||||
{row.message.text}
|
||||
</pre>
|
||||
{(displayedUserMessage.visibleText.trim().length > 0 ||
|
||||
terminalContexts.length > 0) && (
|
||||
<UserMessageBody
|
||||
text={displayedUserMessage.visibleText}
|
||||
terminalContexts={terminalContexts}
|
||||
/>
|
||||
)}
|
||||
<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">
|
||||
{row.message.text && <MessageCopyButton text={row.message.text} />}
|
||||
{displayedUserMessage.copyText && (
|
||||
<MessageCopyButton text={displayedUserMessage.copyText} />
|
||||
)}
|
||||
{canRevertAgentWork && (
|
||||
<Button
|
||||
type="button"
|
||||
@@ -636,6 +661,110 @@ 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,6 +74,13 @@ 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;
|
||||
@@ -120,28 +127,31 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"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",
|
||||
"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",
|
||||
)}
|
||||
disabled={props.disabled}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span
|
||||
className={cn("flex min-w-0 items-center gap-2", props.compact ? "max-w-36" : undefined)}
|
||||
className={cn(
|
||||
"flex min-w-0 w-full items-center gap-2 overflow-hidden",
|
||||
props.compact ? "max-w-36" : undefined,
|
||||
)}
|
||||
>
|
||||
<ProviderIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
props.provider === "claudeAgent" ? "text-[#d97757]" : "text-muted-foreground/70",
|
||||
props.provider === "claudeAgent" && props.ultrathinkActive
|
||||
providerIconClassName(activeProvider, "text-muted-foreground/70"),
|
||||
activeProvider === "claudeAgent" && props.ultrathinkActive
|
||||
? "ultrathink-chroma"
|
||||
: undefined,
|
||||
)}
|
||||
/>
|
||||
<span className="truncate">{selectedModelLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
<span className="min-w-0 flex-1 truncate">{selectedModelLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
@@ -171,7 +181,10 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
<MenuSubTrigger>
|
||||
<OptionIcon
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0 text-muted-foreground/85"
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
providerIconClassName(option.value, "text-muted-foreground/85"),
|
||||
)}
|
||||
/>
|
||||
{option.label}
|
||||
</MenuSubTrigger>
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
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,5 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { appendTerminalContextsToPrompt } from "../lib/terminalContext";
|
||||
import { buildInlineTerminalContextText } from "./chat/userMessageTerminalContexts";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
|
||||
describe("estimateTimelineMessageHeight", () => {
|
||||
@@ -75,6 +77,35 @@ 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,3 +1,6 @@
|
||||
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;
|
||||
@@ -75,7 +78,17 @@ export function estimateTimelineMessageHeight(
|
||||
|
||||
if (message.role === "user") {
|
||||
const charsPerLine = estimateCharsPerLineForUser(layout.timelineWidthPx);
|
||||
const estimatedLines = estimateWrappedLineCount(message.text, charsPerLine);
|
||||
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 attachmentCount = message.attachments?.length ?? 0;
|
||||
const attachmentRows = Math.ceil(attachmentCount / ATTACHMENTS_PER_ROW);
|
||||
const attachmentHeight = attachmentRows * USER_ATTACHMENT_ROW_HEIGHT_PX;
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
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 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 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",
|
||||
{
|
||||
defaultVariants: {
|
||||
size: "default",
|
||||
@@ -834,7 +834,7 @@ function SidebarMenuAction({
|
||||
}) {
|
||||
const defaultProps = {
|
||||
className: cn(
|
||||
"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",
|
||||
"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",
|
||||
// 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 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 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",
|
||||
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
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", () => {
|
||||
@@ -24,4 +25,17 @@ 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,3 +1,8 @@
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
} from "./lib/terminalContext";
|
||||
|
||||
export type ComposerPromptSegment =
|
||||
| {
|
||||
type: "text";
|
||||
@@ -6,6 +11,10 @@ export type ComposerPromptSegment =
|
||||
| {
|
||||
type: "mention";
|
||||
path: string;
|
||||
}
|
||||
| {
|
||||
type: "terminal-context";
|
||||
context: TerminalContextDraft | null;
|
||||
};
|
||||
|
||||
const MENTION_TOKEN_REGEX = /(^|\s)@([^\s@]+)(?=\s)/g;
|
||||
@@ -20,14 +29,14 @@ function pushTextSegment(segments: ComposerPromptSegment[], text: string): void
|
||||
segments.push({ type: "text", text });
|
||||
}
|
||||
|
||||
export function splitPromptIntoComposerSegments(prompt: string): ComposerPromptSegment[] {
|
||||
function splitPromptTextIntoComposerSegments(text: string): ComposerPromptSegment[] {
|
||||
const segments: ComposerPromptSegment[] = [];
|
||||
if (!prompt) {
|
||||
if (!text) {
|
||||
return segments;
|
||||
}
|
||||
|
||||
let cursor = 0;
|
||||
for (const match of prompt.matchAll(MENTION_TOKEN_REGEX)) {
|
||||
for (const match of text.matchAll(MENTION_TOKEN_REGEX)) {
|
||||
const fullMatch = match[0];
|
||||
const prefix = match[1] ?? "";
|
||||
const path = match[2] ?? "";
|
||||
@@ -36,20 +45,55 @@ export function splitPromptIntoComposerSegments(prompt: string): ComposerPromptS
|
||||
const mentionEnd = mentionStart + fullMatch.length - prefix.length;
|
||||
|
||||
if (mentionStart > cursor) {
|
||||
pushTextSegment(segments, prompt.slice(cursor, mentionStart));
|
||||
pushTextSegment(segments, text.slice(cursor, mentionStart));
|
||||
}
|
||||
|
||||
if (path.length > 0) {
|
||||
segments.push({ type: "mention", path });
|
||||
} else {
|
||||
pushTextSegment(segments, prompt.slice(mentionStart, mentionEnd));
|
||||
pushTextSegment(segments, text.slice(mentionStart, mentionEnd));
|
||||
}
|
||||
|
||||
cursor = mentionEnd;
|
||||
}
|
||||
|
||||
if (cursor < prompt.length) {
|
||||
pushTextSegment(segments, prompt.slice(cursor));
|
||||
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)));
|
||||
}
|
||||
|
||||
return segments;
|
||||
|
||||
@@ -5,10 +5,11 @@ import {
|
||||
collapseExpandedComposerCursor,
|
||||
detectComposerTrigger,
|
||||
expandCollapsedComposerCursor,
|
||||
isCollapsedCursorAdjacentToMention,
|
||||
isCollapsedCursorAdjacentToInlineToken,
|
||||
parseStandaloneComposerSlashCommand,
|
||||
replaceTextRange,
|
||||
} from "./composer-logic";
|
||||
import { INLINE_TERMINAL_CONTEXT_PLACEHOLDER } from "./lib/terminalContext";
|
||||
|
||||
describe("detectComposerTrigger", () => {
|
||||
it("detects @path trigger at cursor", () => {
|
||||
@@ -192,16 +193,16 @@ describe("replaceTextRange trailing space consumption", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("isCollapsedCursorAdjacentToMention", () => {
|
||||
describe("isCollapsedCursorAdjacentToInlineToken", () => {
|
||||
it("returns false when no mention exists", () => {
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention("plain text", 6, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken("plain text", 6, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps @query typing non-adjacent while no mention pill exists", () => {
|
||||
const text = "hello @pac";
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, text.length, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, text.length, "right")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects left adjacency only when cursor is directly after a mention", () => {
|
||||
@@ -209,9 +210,9 @@ describe("isCollapsedCursorAdjacentToMention", () => {
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "left")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd + 1, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd, "left")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionStart, "left")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToInlineToken(text, mentionEnd + 1, "left")).toBe(false);
|
||||
});
|
||||
|
||||
it("detects right adjacency only when cursor is directly before a mention", () => {
|
||||
@@ -219,9 +220,18 @@ describe("isCollapsedCursorAdjacentToMention", () => {
|
||||
const mentionStart = "open ".length;
|
||||
const mentionEnd = mentionStart + 1;
|
||||
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart, "right")).toBe(true);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionEnd, "right")).toBe(false);
|
||||
expect(isCollapsedCursorAdjacentToMention(text, mentionStart - 1, "right")).toBe(false);
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
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";
|
||||
@@ -11,6 +12,9 @@ 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;
|
||||
@@ -18,7 +22,13 @@ function clampCursor(text: string, cursor: number): number {
|
||||
}
|
||||
|
||||
function isWhitespace(char: string): boolean {
|
||||
return char === " " || char === "\n" || char === "\t" || char === "\r";
|
||||
return (
|
||||
char === " " ||
|
||||
char === "\n" ||
|
||||
char === "\t" ||
|
||||
char === "\r" ||
|
||||
char === INLINE_TERMINAL_CONTEXT_PLACEHOLDER
|
||||
);
|
||||
}
|
||||
|
||||
function tokenStartForCursor(text: string, cursor: number): number {
|
||||
@@ -49,6 +59,14 @@ 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) {
|
||||
@@ -62,13 +80,18 @@ export function expandCollapsedComposerCursor(text: string, cursorInput: number)
|
||||
}
|
||||
|
||||
function collapsedSegmentLength(
|
||||
segment: { type: "text"; text: string } | { type: "mention" },
|
||||
segment: { type: "text"; text: string } | { type: "mention" } | { type: "terminal-context" },
|
||||
): number {
|
||||
return segment.type === "mention" ? 1 : segment.text.length;
|
||||
if (segment.type === "text") {
|
||||
return segment.text.length;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
function clampCollapsedComposerCursorForSegments(
|
||||
segments: ReadonlyArray<{ type: "text"; text: string } | { type: "mention" }>,
|
||||
segments: ReadonlyArray<
|
||||
{ type: "text"; text: string } | { type: "mention" } | { type: "terminal-context" }
|
||||
>,
|
||||
cursorInput: number,
|
||||
): number {
|
||||
const collapsedLength = segments.reduce(
|
||||
@@ -111,6 +134,14 @@ 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) {
|
||||
@@ -123,13 +154,13 @@ export function collapseExpandedComposerCursor(text: string, cursorInput: number
|
||||
return collapsedCursor;
|
||||
}
|
||||
|
||||
export function isCollapsedCursorAdjacentToMention(
|
||||
export function isCollapsedCursorAdjacentToInlineToken(
|
||||
text: string,
|
||||
cursorInput: number,
|
||||
direction: "left" | "right",
|
||||
): boolean {
|
||||
const segments = splitPromptIntoComposerSegments(text);
|
||||
if (!segments.some((segment) => segment.type === "mention")) {
|
||||
if (!segments.some(isInlineTokenSegment)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -137,7 +168,7 @@ export function isCollapsedCursorAdjacentToMention(
|
||||
let collapsedOffset = 0;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
if (isInlineTokenSegment(segment)) {
|
||||
if (direction === "left" && cursor === collapsedOffset + 1) {
|
||||
return true;
|
||||
}
|
||||
@@ -151,6 +182,8 @@ export function isCollapsedCursorAdjacentToMention(
|
||||
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,11 +1,19 @@
|
||||
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;
|
||||
@@ -34,6 +42,26 @@ 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;
|
||||
@@ -158,6 +186,236 @@ 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");
|
||||
@@ -337,8 +595,8 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore codex fast mode", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-service-tier");
|
||||
describe("composerDraftStore modelOptions", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model-options");
|
||||
|
||||
beforeEach(() => {
|
||||
useComposerDraftStore.setState({
|
||||
@@ -348,17 +606,39 @@ describe("composerDraftStore codex fast mode", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("stores codex fast mode in the draft", () => {
|
||||
it("stores provider-scoped model options in the draft", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setCodexFastMode(threadId, true);
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.codexFastMode).toBe(true);
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("clears codex fast mode when reset to the default", () => {
|
||||
it("drops default-only model options from the draft", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setCodexFastMode(threadId, true);
|
||||
store.setCodexFastMode(threadId, false);
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
+620
-252
File diff suppressed because it is too large.
Load diff
@@ -112,6 +112,7 @@ export function gitCheckoutMutationOptions(input: {
|
||||
export function gitRunStackedActionMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
model?: string | null;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
|
||||
@@ -134,6 +135,7 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
});
|
||||
},
|
||||
onSettled: async () => {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
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();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,356 @@
|
||||
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 } from "@t3tools/contracts";
|
||||
import { type ProviderKind, DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
|
||||
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import { getAppModelOptions, MAX_CUSTOM_MODEL_LENGTH, useAppSettings } from "../appSettings";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
@@ -126,6 +126,17 @@ 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);
|
||||
@@ -516,6 +527,65 @@ 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,4 +1,10 @@
|
||||
import { EventId, MessageId, TurnId, type OrchestrationThreadActivity } from "@t3tools/contracts";
|
||||
import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -10,6 +16,8 @@ import {
|
||||
deriveTimelineEntries,
|
||||
deriveWorkLogEntries,
|
||||
findLatestProposedPlan,
|
||||
findSidebarProposedPlan,
|
||||
hasActionableProposedPlan,
|
||||
hasToolActivityForTurn,
|
||||
isLatestTurnSettled,
|
||||
} from "./session-logic";
|
||||
@@ -33,6 +41,7 @@ function makeActivity(overrides: {
|
||||
tone: overrides.tone ?? "tool",
|
||||
payload,
|
||||
turnId: overrides.turnId ? TurnId.makeUnsafe(overrides.turnId) : null,
|
||||
workUnitId: null,
|
||||
...(overrides.sequence !== undefined ? { sequence: overrides.sequence } : {}),
|
||||
};
|
||||
}
|
||||
@@ -269,6 +278,8 @@ 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",
|
||||
},
|
||||
@@ -276,6 +287,8 @@ 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",
|
||||
},
|
||||
@@ -283,6 +296,8 @@ 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",
|
||||
},
|
||||
@@ -293,6 +308,8 @@ 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",
|
||||
});
|
||||
@@ -305,6 +322,8 @@ 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",
|
||||
},
|
||||
@@ -312,6 +331,8 @@ 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",
|
||||
},
|
||||
@@ -323,6 +344,133 @@ 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[] = [
|
||||
@@ -410,6 +558,42 @@ 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({
|
||||
@@ -531,6 +715,8 @@ 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",
|
||||
},
|
||||
@@ -550,6 +736,8 @@ describe("deriveTimelineEntries", () => {
|
||||
kind: "proposed-plan",
|
||||
proposedPlan: {
|
||||
planMarkdown: "# Ship it",
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type ProviderKind,
|
||||
type ToolLifecycleItemType,
|
||||
type UserInputQuestion,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
@@ -14,6 +15,7 @@ import type {
|
||||
ChatMessage,
|
||||
ProposedPlan,
|
||||
SessionPhase,
|
||||
Thread,
|
||||
ThreadSession,
|
||||
TurnDiffSummary,
|
||||
} from "./types";
|
||||
@@ -72,6 +74,8 @@ export interface LatestProposedPlanState {
|
||||
updatedAt: string;
|
||||
turnId: TurnId | null;
|
||||
planMarkdown: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}
|
||||
|
||||
export type TimelineEntry =
|
||||
@@ -374,13 +378,7 @@ export function findLatestProposedPlan(
|
||||
)
|
||||
.at(-1);
|
||||
if (matchingTurnPlan) {
|
||||
return {
|
||||
id: matchingTurnPlan.id,
|
||||
createdAt: matchingTurnPlan.createdAt,
|
||||
updatedAt: matchingTurnPlan.updatedAt,
|
||||
turnId: matchingTurnPlan.turnId,
|
||||
planMarkdown: matchingTurnPlan.planMarkdown,
|
||||
};
|
||||
return toLatestProposedPlanState(matchingTurnPlan);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -394,13 +392,37 @@ export function findLatestProposedPlan(
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
id: latestPlan.id,
|
||||
createdAt: latestPlan.createdAt,
|
||||
updatedAt: latestPlan.updatedAt,
|
||||
turnId: latestPlan.turnId,
|
||||
planMarkdown: latestPlan.planMarkdown,
|
||||
};
|
||||
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;
|
||||
}
|
||||
|
||||
export function deriveWorkLogEntries(
|
||||
@@ -413,6 +435,7 @@ 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"
|
||||
@@ -454,6 +477,30 @@ 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;
|
||||
}
|
||||
|
||||
@@ -67,6 +67,7 @@ function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"
|
||||
messages: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
...overrides,
|
||||
|
||||
@@ -297,6 +297,8 @@ 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,6 +53,8 @@ export interface ProposedPlan {
|
||||
id: OrchestrationProposedPlanId;
|
||||
turnId: TurnId | null;
|
||||
planMarkdown: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
@@ -75,6 +75,17 @@ 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(".")) {
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
"t3": "./dist/index.mjs",
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.76",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
@@ -153,6 +153,7 @@
|
||||
"scripts": {
|
||||
"name": "@t3tools/scripts",
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
@@ -183,7 +184,7 @@
|
||||
"vitest": "^4.0.0",
|
||||
},
|
||||
"packages": {
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]6", "", { "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.34.2", "@img/sharp-darwin-x64": "^0.34.2", "@img/sharp-linux-arm": "^0.34.2", "@img/sharp-linux-arm64": "^0.34.2", "@img/sharp-linux-x64": "^0.34.2", "@img/sharp-linuxmusl-arm64": "^0.34.2", "@img/sharp-linuxmusl-x64": "^0.34.2", "@img/sharp-win32-arm64": "^0.34.2", "@img/sharp-win32-x64": "^0.34.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-HZxvnT8ZWkzCnQygaYCA0dl8RSUzuVbxE1YG4ecy6vh4nQbTT36CxUxBy+QVdR12pPQluncC0mCOLhI2918Eaw=="],
|
||||
"@anthropic-ai/claude-agent-sdk": ["@anthropic-ai/[email protected]7", "", { "optionalDependencies": { "@img/sharp-darwin-arm64": "^0.34.2", "@img/sharp-darwin-x64": "^0.34.2", "@img/sharp-linux-arm": "^0.34.2", "@img/sharp-linux-arm64": "^0.34.2", "@img/sharp-linux-x64": "^0.34.2", "@img/sharp-linuxmusl-arm64": "^0.34.2", "@img/sharp-linuxmusl-x64": "^0.34.2", "@img/sharp-win32-arm64": "^0.34.2", "@img/sharp-win32-x64": "^0.34.2" }, "peerDependencies": { "zod": "^4.0.0" } }, "sha512-t+R1BW3ahCFMNM7/8WJq7+Gw9KPA9Cl7UUK8fWPokJZ75cf/xwEd9MqB+MVNoQT45dJiom/wxybT7tqYPkCqyg=="],
|
||||
|
||||
"@astrojs/check": ["@astrojs/[email protected]", "", { "dependencies": { "@astrojs/language-server": "^2.16.5", "chokidar": "^4.0.3", "kleur": "^4.1.5", "yargs": "^17.7.2" }, "peerDependencies": { "typescript": "^5.0.0" }, "bin": { "astro-check": "bin/astro-check.js" } }, "sha512-LDng8446QLS5ToKjRHd3bgUdirvemVVExV7nRyJfW2wV36xuv7vDxwy5NWN9zqeSEDgg0Tv84sP+T3yEq+Zlkw=="],
|
||||
|
||||
|
||||
@@ -27,6 +27,8 @@ export const MessageId = makeEntityId("MessageId");
|
||||
export type MessageId = typeof MessageId.Type;
|
||||
export const TurnId = makeEntityId("TurnId");
|
||||
export type TurnId = typeof TurnId.Type;
|
||||
export const WorkUnitId = makeEntityId("WorkUnitId");
|
||||
export type WorkUnitId = typeof WorkUnitId.Type;
|
||||
|
||||
export const ProviderItemId = makeEntityId("ProviderItemId");
|
||||
export type ProviderItemId = typeof ProviderItemId.Type;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Schema } from "effect";
|
||||
import { Option, Schema } from "effect";
|
||||
import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "./model";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
|
||||
@@ -64,6 +65,9 @@ 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;
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ export type CodexModelOptions = typeof CodexModelOptions.Type;
|
||||
export const ClaudeModelOptions = Schema.Struct({
|
||||
thinking: Schema.optional(Schema.Boolean),
|
||||
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)),
|
||||
fastMode: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
|
||||
|
||||
@@ -33,6 +34,7 @@ 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" },
|
||||
@@ -57,6 +59,7 @@ 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,7 +6,11 @@ import {
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationProposedPlan,
|
||||
OrchestrationSession,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadActivity,
|
||||
ProjectCreateCommand,
|
||||
ThreadTurnStartCommand,
|
||||
ThreadCreatedPayload,
|
||||
@@ -21,7 +25,11 @@ 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 decodeOrchestrationThread = Schema.decodeUnknownEffect(OrchestrationThread);
|
||||
const decodeOrchestrationThreadActivity = Schema.decodeUnknownEffect(OrchestrationThreadActivity);
|
||||
const decodeThreadCreatedPayload = Schema.decodeUnknownEffect(ThreadCreatedPayload);
|
||||
|
||||
it.effect("parses turn diff input when fromTurnCount <= toTurnCount", () =>
|
||||
@@ -186,6 +194,31 @@ 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",
|
||||
() =>
|
||||
@@ -198,9 +231,49 @@ 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({
|
||||
@@ -216,3 +289,73 @@ 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");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("defaults activity work unit ids for historical rows", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeOrchestrationThreadActivity({
|
||||
id: "activity-1",
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "Runtime note",
|
||||
payload: {},
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.strictEqual(parsed.workUnitId, null);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("defaults thread work units for historical rows", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeOrchestrationThread({
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
});
|
||||
assert.deepStrictEqual(parsed.workUnits, []);
|
||||
}),
|
||||
);
|
||||
@@ -13,6 +13,9 @@ import {
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
TurnId,
|
||||
RuntimeItemId,
|
||||
RuntimeTaskId,
|
||||
WorkUnitId,
|
||||
} from "./baseSchemas";
|
||||
|
||||
export const ORCHESTRATION_WS_METHODS = {
|
||||
@@ -174,11 +177,18 @@ 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",
|
||||
@@ -238,11 +248,49 @@ export const OrchestrationThreadActivity = Schema.Struct({
|
||||
summary: TrimmedNonEmptyString,
|
||||
payload: Schema.Unknown,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
workUnitId: Schema.NullOr(WorkUnitId).pipe(Schema.withDecodingDefault(() => null)),
|
||||
sequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
export type OrchestrationThreadActivity = typeof OrchestrationThreadActivity.Type;
|
||||
|
||||
export const OrchestrationWorkUnitKind = Schema.Literals(["primary_agent", "delegated_agent"]);
|
||||
export type OrchestrationWorkUnitKind = typeof OrchestrationWorkUnitKind.Type;
|
||||
|
||||
export const OrchestrationWorkUnitState = Schema.Literals([
|
||||
"queued",
|
||||
"running",
|
||||
"completed",
|
||||
"failed",
|
||||
"stopped",
|
||||
"cancelled",
|
||||
]);
|
||||
export type OrchestrationWorkUnitState = typeof OrchestrationWorkUnitState.Type;
|
||||
|
||||
export const OrchestrationWorkUnitProviderRefs = Schema.Struct({
|
||||
runtimeTaskId: Schema.optional(RuntimeTaskId),
|
||||
runtimeItemId: Schema.optional(RuntimeItemId),
|
||||
providerThreadId: Schema.optional(TrimmedNonEmptyString),
|
||||
providerTurnId: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type OrchestrationWorkUnitProviderRefs = typeof OrchestrationWorkUnitProviderRefs.Type;
|
||||
|
||||
export const OrchestrationWorkUnit = Schema.Struct({
|
||||
id: WorkUnitId,
|
||||
turnId: TurnId,
|
||||
parentWorkUnitId: Schema.NullOr(WorkUnitId),
|
||||
kind: OrchestrationWorkUnitKind,
|
||||
state: OrchestrationWorkUnitState,
|
||||
title: TrimmedNonEmptyString,
|
||||
detail: Schema.NullOr(TrimmedNonEmptyString),
|
||||
spawnedByActivityId: Schema.NullOr(EventId),
|
||||
providerRefs: Schema.optional(OrchestrationWorkUnitProviderRefs),
|
||||
startedAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
completedAt: Schema.NullOr(IsoDateTime),
|
||||
});
|
||||
export type OrchestrationWorkUnit = typeof OrchestrationWorkUnit.Type;
|
||||
|
||||
const OrchestrationLatestTurnState = Schema.Literals([
|
||||
"running",
|
||||
"interrupted",
|
||||
@@ -258,6 +306,7 @@ 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;
|
||||
|
||||
@@ -279,6 +328,7 @@ export const OrchestrationThread = Schema.Struct({
|
||||
messages: Schema.Array(OrchestrationMessage),
|
||||
proposedPlans: Schema.Array(OrchestrationProposedPlan).pipe(Schema.withDecodingDefault(() => [])),
|
||||
activities: Schema.Array(OrchestrationThreadActivity),
|
||||
workUnits: Schema.Array(OrchestrationWorkUnit).pipe(Schema.withDecodingDefault(() => [])),
|
||||
checkpoints: Schema.Array(OrchestrationCheckpointSummary),
|
||||
session: Schema.NullOr(OrchestrationSession),
|
||||
});
|
||||
@@ -385,6 +435,7 @@ export const ThreadTurnStartCommand = Schema.Struct({
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
),
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -405,6 +456,7 @@ const ClientThreadTurnStartCommand = Schema.Struct({
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -543,6 +595,14 @@ const ThreadActivityAppendCommand = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadWorkUnitUpsertCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.work-unit.upsert"),
|
||||
commandId: CommandId,
|
||||
threadId: ThreadId,
|
||||
workUnit: OrchestrationWorkUnit,
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadRevertCompleteCommand = Schema.Struct({
|
||||
type: Schema.Literal("thread.revert.complete"),
|
||||
commandId: CommandId,
|
||||
@@ -558,6 +618,7 @@ const InternalOrchestrationCommand = Schema.Union([
|
||||
ThreadProposedPlanUpsertCommand,
|
||||
ThreadTurnDiffCompleteCommand,
|
||||
ThreadActivityAppendCommand,
|
||||
ThreadWorkUnitUpsertCommand,
|
||||
ThreadRevertCompleteCommand,
|
||||
]);
|
||||
export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;
|
||||
@@ -589,6 +650,7 @@ export const OrchestrationEventType = Schema.Literals([
|
||||
"thread.proposed-plan-upserted",
|
||||
"thread.turn-diff-completed",
|
||||
"thread.activity-appended",
|
||||
"thread.work-unit-upserted",
|
||||
]);
|
||||
export type OrchestrationEventType = typeof OrchestrationEventType.Type;
|
||||
|
||||
@@ -687,6 +749,7 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
),
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
|
||||
@@ -752,6 +815,11 @@ export const ThreadActivityAppendedPayload = Schema.Struct({
|
||||
activity: OrchestrationThreadActivity,
|
||||
});
|
||||
|
||||
export const ThreadWorkUnitUpsertedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
workUnit: OrchestrationWorkUnit,
|
||||
});
|
||||
|
||||
export const OrchestrationEventMetadata = Schema.Struct({
|
||||
providerTurnId: Schema.optional(TrimmedNonEmptyString),
|
||||
providerItemId: Schema.optional(ProviderItemId),
|
||||
@@ -874,6 +942,11 @@ export const OrchestrationEvent = Schema.Union([
|
||||
type: Schema.Literal("thread.activity-appended"),
|
||||
payload: ThreadActivityAppendedPayload,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...EventBaseFields,
|
||||
type: Schema.Literal("thread.work-unit-upserted"),
|
||||
payload: ThreadWorkUnitUpsertedPayload,
|
||||
}),
|
||||
]);
|
||||
export type OrchestrationEvent = typeof OrchestrationEvent.Type;
|
||||
|
||||
|
||||
@@ -53,6 +53,7 @@ describe("ProviderSessionStartInput", () => {
|
||||
claudeAgent: {
|
||||
thinking: true,
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
providerOptions: {
|
||||
@@ -67,6 +68,7 @@ describe("ProviderSessionStartInput", () => {
|
||||
expect(parsed.provider).toBe("claudeAgent");
|
||||
expect(parsed.modelOptions?.claudeAgent?.thinking).toBe(true);
|
||||
expect(parsed.modelOptions?.claudeAgent?.effort).toBe("max");
|
||||
expect(parsed.modelOptions?.claudeAgent?.fastMode).toBe(true);
|
||||
expect(parsed.providerOptions?.claudeAgent?.binaryPath).toBe("/usr/local/bin/claude");
|
||||
expect(parsed.providerOptions?.claudeAgent?.permissionMode).toBe("plan");
|
||||
expect(parsed.providerOptions?.claudeAgent?.maxThinkingTokens).toBe(12_000);
|
||||
@@ -99,10 +101,12 @@ describe("ProviderSendTurnInput", () => {
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "ultrathink",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.modelOptions?.claudeAgent?.effort).toBe("ultrathink");
|
||||
expect(parsed.modelOptions?.claudeAgent?.fastMode).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -16,10 +16,18 @@ import {
|
||||
getModelOptions,
|
||||
getReasoningEffortOptions,
|
||||
inferProviderForModel,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptions,
|
||||
normalizeCodexModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveReasoningEffortForProvider,
|
||||
resolveModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
supportsClaudeAdaptiveReasoning,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeMaxEffort,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
} from "./model";
|
||||
|
||||
describe("normalizeModelSlug", () => {
|
||||
@@ -91,8 +99,8 @@ describe("getReasoningEffortOptions", () => {
|
||||
expect(getReasoningEffortOptions("codex")).toEqual(REASONING_EFFORT_OPTIONS_BY_PROVIDER.codex);
|
||||
});
|
||||
|
||||
it("returns claude effort options for claudeAgent", () => {
|
||||
expect(getReasoningEffortOptions("claudeAgent")).toEqual([
|
||||
it("returns claude effort options for Opus 4.6", () => {
|
||||
expect(getReasoningEffortOptions("claudeAgent", "claude-opus-4-6")).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
@@ -100,6 +108,19 @@ 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", () => {
|
||||
@@ -156,8 +177,8 @@ describe("applyClaudePromptEffortPrefix", () => {
|
||||
});
|
||||
|
||||
describe("getEffectiveClaudeCodeEffort", () => {
|
||||
it("maps ultrathink to max for Claude runtime configuration", () => {
|
||||
expect(getEffectiveClaudeCodeEffort("ultrathink")).toBe("max");
|
||||
it("does not persist ultrathink into Claude runtime configuration", () => {
|
||||
expect(getEffectiveClaudeCodeEffort("ultrathink")).toBeNull();
|
||||
expect(getEffectiveClaudeCodeEffort("high")).toBe("high");
|
||||
});
|
||||
|
||||
@@ -166,3 +187,95 @@ describe("getEffectiveClaudeCodeEffort", () => {
|
||||
expect(getEffectiveClaudeCodeEffort(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
expect(supportsClaudeFastMode("opus")).toBe(true);
|
||||
expect(supportsClaudeFastMode("claude-sonnet-4-6")).toBe(false);
|
||||
expect(supportsClaudeFastMode("claude-haiku-4-5")).toBe(false);
|
||||
expect(supportsClaudeFastMode(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeUltrathinkKeyword", () => {
|
||||
it("only enables ultrathink keyword handling for Opus 4.6 and Sonnet 4.6", () => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 104 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user