Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f65e38f3d1 | ||
|
|
d25090cf6d | ||
|
|
ae39bacf0e | ||
|
|
1ea17026ee | ||
|
|
649f4328ea | ||
|
|
7db034905b | ||
|
|
57f6bf7edb | ||
|
|
0baf1986e8 | ||
|
|
ae7e88b0e0 | ||
|
|
1916ac6d55 | ||
|
|
343061a053 |
No files matched your search
@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
|
||||
input.readMagicDnsName ??
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.catch(() => Effect.succeed<string | null>(null)),
|
||||
Effect.orElseSucceed(() => null),
|
||||
);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useAuth, useUser, useUserProfileModal } from "@clerk/expo";
|
||||
import { useAuth, useUser } from "@clerk/expo";
|
||||
import * as Notifications from "expo-notifications";
|
||||
import { Link, Stack, useRouter } from "expo-router";
|
||||
import { SymbolView } from "expo-symbols";
|
||||
@@ -68,7 +68,6 @@ function ConfiguredSettingsRouteScreen() {
|
||||
const { push } = useRouter();
|
||||
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const { user } = useUser();
|
||||
const { isAvailable: isUserProfileModalAvailable, presentUserProfile } = useUserProfileModal();
|
||||
const { savedConnectionsById } = useRemoteEnvironmentState();
|
||||
const [notificationStatus, setNotificationStatus] = useState<NotificationStatus>("checking");
|
||||
const [liveActivityStatus, setLiveActivityStatus] = useState<LiveActivityStatus>("checking");
|
||||
@@ -266,15 +265,11 @@ function ConfiguredSettingsRouteScreen() {
|
||||
push("/settings/waitlist");
|
||||
return;
|
||||
}
|
||||
if (isUserProfileModalAvailable) {
|
||||
void presentUserProfile();
|
||||
return;
|
||||
}
|
||||
Alert.alert(
|
||||
"T3 Cloud unavailable",
|
||||
"Native T3 Cloud account management is not available in this build.",
|
||||
);
|
||||
}, [isLoaded, isSignedIn, isUserProfileModalAvailable, presentUserProfile, push]);
|
||||
}, [isLoaded, isSignedIn, push]);
|
||||
|
||||
return (
|
||||
<View collapsable={false} className="flex-1 bg-sheet">
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
"test": "vp test run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.154",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.3.170",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/platform-node-shared": "catalog:",
|
||||
|
||||
@@ -22,6 +22,7 @@ const emitXAiAskUserQuestion = process.env.T3_ACP_EMIT_XAI_ASK_USER_QUESTION ===
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
const promptDelayMs = Number(process.env.T3_ACP_PROMPT_DELAY_MS ?? "0");
|
||||
const permissionOptionIds = {
|
||||
allowOnce: process.env.T3_ACP_ALLOW_ONCE_OPTION_ID ?? "allow-once",
|
||||
allowAlways: process.env.T3_ACP_ALLOW_ALWAYS_OPTION_ID ?? "allow-always",
|
||||
@@ -364,6 +365,10 @@ const program = Effect.gen(function* () {
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
|
||||
if (Number.isFinite(promptDelayMs) && promptDelayMs > 0) {
|
||||
yield* Effect.sleep(`${promptDelayMs} millis`);
|
||||
}
|
||||
|
||||
if (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { ProviderInstanceId } from "@t3tools/contracts";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
|
||||
import { getCodexServiceTierOptionValue } from "./codexModelOptions.ts";
|
||||
|
||||
it("returns the selected Codex service tier id", () => {
|
||||
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.5", [
|
||||
{ id: "serviceTier", value: "flex" },
|
||||
]);
|
||||
|
||||
assert.equal(getCodexServiceTierOptionValue(selection), "flex");
|
||||
});
|
||||
|
||||
it("keeps legacy persisted fast mode selections working", () => {
|
||||
const selection = createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
|
||||
{ id: "fastMode", value: true },
|
||||
]);
|
||||
|
||||
assert.equal(getCodexServiceTierOptionValue(selection), "fast");
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { ModelSelection } from "@t3tools/contracts";
|
||||
import {
|
||||
getModelSelectionBooleanOptionValue,
|
||||
getModelSelectionStringOptionValue,
|
||||
} from "@t3tools/shared/model";
|
||||
|
||||
export function getCodexServiceTierOptionValue(
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
): string | undefined {
|
||||
return (
|
||||
getModelSelectionStringOptionValue(modelSelection, "serviceTier") ??
|
||||
(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true ? "fast" : undefined)
|
||||
);
|
||||
}
|
||||
@@ -747,7 +747,7 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
);
|
||||
const readRemoteStatus = Effect.fn("readRemoteStatus")(function* (cwd: string) {
|
||||
const details = yield* gitCore
|
||||
.statusDetails(cwd)
|
||||
.statusDetailsRemote(cwd)
|
||||
.pipe(Effect.catchIf(isNotGitRepositoryError, () => Effect.succeed(null)));
|
||||
if (details === null || !details.isRepo) {
|
||||
return null;
|
||||
|
||||
@@ -1232,6 +1232,227 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps the turn running across interim assistant messages until the session ends", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const threadId = ThreadId.make("thread-turn-lifecycle");
|
||||
const turnId = TurnId.make("turn-lifecycle-1");
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-tl1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-tl1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-tl1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-turn-lifecycle"),
|
||||
title: "Turn lifecycle",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("claude"),
|
||||
model: "claude-opus",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.make("evt-tl2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-01-01T00:00:01.000Z",
|
||||
commandId: CommandId.make("cmd-tl2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-tl2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "claude",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: turnId,
|
||||
lastError: null,
|
||||
updatedAt: "2026-01-01T00:00:01.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Interim assistant message completes mid-turn (commentary between
|
||||
// tool calls) — the turn must stay running and unsettled.
|
||||
yield* eventStore.append({
|
||||
type: "thread.message-sent",
|
||||
eventId: EventId.make("evt-tl3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-01-01T00:00:05.000Z",
|
||||
commandId: CommandId.make("cmd-tl3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-tl3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
messageId: MessageId.make("message-tl-interim"),
|
||||
role: "assistant",
|
||||
text: "interim commentary",
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: "2026-01-01T00:00:05.000Z",
|
||||
updatedAt: "2026-01-01T00:00:05.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const runningRows = yield* sql<{
|
||||
readonly state: string;
|
||||
readonly completedAt: string | null;
|
||||
}>`
|
||||
SELECT state, completed_at AS "completedAt"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
|
||||
`;
|
||||
assert.deepEqual(runningRows, [{ state: "running", completedAt: null }]);
|
||||
|
||||
// The session leaving "running" is the turn-end signal.
|
||||
yield* eventStore.append({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.make("evt-tl4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: "2026-01-01T00:01:00.000Z",
|
||||
commandId: CommandId.make("cmd-tl4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-tl4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "ready",
|
||||
providerName: "claude",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-01-01T00:01:00.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const settledRows = yield* sql<{
|
||||
readonly state: string;
|
||||
readonly completedAt: string | null;
|
||||
}>`
|
||||
SELECT state, completed_at AS "completedAt"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = ${threadId} AND turn_id = ${turnId}
|
||||
`;
|
||||
assert.deepEqual(settledRows, [
|
||||
{ state: "completed", completedAt: "2026-01-01T00:01:00.000Z" },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("settles a superseded running turn when a new turn becomes active", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
const threadId = ThreadId.make("thread-turn-supersede");
|
||||
const oldTurnId = TurnId.make("turn-superseded");
|
||||
const newTurnId = TurnId.make("turn-steer");
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-ts1"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: now,
|
||||
commandId: CommandId.make("cmd-ts1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-ts1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
projectId: ProjectId.make("project-turn-supersede"),
|
||||
title: "Turn supersede",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "big-pickle",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
const appendRunningSessionSet = (eventId: string, turnId: TurnId, updatedAt: string) =>
|
||||
eventStore.append({
|
||||
type: "thread.session-set",
|
||||
eventId: EventId.make(eventId),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: threadId,
|
||||
occurredAt: updatedAt,
|
||||
commandId: CommandId.make(`cmd-${eventId}`),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make(`cmd-${eventId}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "opencode",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: turnId,
|
||||
lastError: null,
|
||||
updatedAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendRunningSessionSet("evt-ts2", oldTurnId, "2026-01-01T00:00:01.000Z");
|
||||
// A steer: a new turn becomes active without the provider ever
|
||||
// completing the previous one.
|
||||
yield* appendRunningSessionSet("evt-ts3", newTurnId, "2026-01-01T00:00:30.000Z");
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const rows = yield* sql<{
|
||||
readonly turnId: string;
|
||||
readonly state: string;
|
||||
readonly completedAt: string | null;
|
||||
}>`
|
||||
SELECT turn_id AS "turnId", state, completed_at AS "completedAt"
|
||||
FROM projection_turns
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY requested_at
|
||||
`;
|
||||
assert.deepEqual(rows, [
|
||||
{ turnId: oldTurnId, state: "completed", completedAt: "2026-01-01T00:00:30.000Z" },
|
||||
{ turnId: newTurnId, state: "running", completedAt: null },
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps accumulated assistant text when completion payload text is empty", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
@@ -1656,6 +1877,142 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clears stale pending user input from projected shell summaries", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
|
||||
eventStore
|
||||
.append(event)
|
||||
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "project.created",
|
||||
eventId: EventId.make("evt-stale-user-input-1"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: ProjectId.make("project-stale-user-input"),
|
||||
occurredAt: "2026-02-26T12:35:00.000Z",
|
||||
commandId: CommandId.make("cmd-stale-user-input-1"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-user-input-1"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: ProjectId.make("project-stale-user-input"),
|
||||
title: "Project Stale User Input",
|
||||
workspaceRoot: "/tmp/project-stale-user-input",
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:35:00.000Z",
|
||||
updatedAt: "2026-02-26T12:35:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.created",
|
||||
eventId: EventId.make("evt-stale-user-input-2"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-user-input"),
|
||||
occurredAt: "2026-02-26T12:35:01.000Z",
|
||||
commandId: CommandId.make("cmd-stale-user-input-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-user-input-2"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-user-input"),
|
||||
projectId: ProjectId.make("project-stale-user-input"),
|
||||
title: "Thread Stale User Input",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T12:35:01.000Z",
|
||||
updatedAt: "2026-02-26T12:35:01.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-stale-user-input-3"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-user-input"),
|
||||
occurredAt: "2026-02-26T12:35:02.000Z",
|
||||
commandId: CommandId.make("cmd-stale-user-input-3"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-user-input-3"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-user-input"),
|
||||
activity: {
|
||||
id: EventId.make("activity-stale-user-input-requested"),
|
||||
tone: "info",
|
||||
kind: "user-input.requested",
|
||||
summary: "User input requested",
|
||||
payload: {
|
||||
requestId: "user-input-request-stale-1",
|
||||
questions: [
|
||||
{
|
||||
id: "sandbox_mode",
|
||||
header: "Sandbox",
|
||||
question: "Which mode should be used?",
|
||||
options: [
|
||||
{
|
||||
label: "workspace-write",
|
||||
description: "Allow workspace writes only",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:35:02.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* appendAndProject({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.make("evt-stale-user-input-4"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-stale-user-input"),
|
||||
occurredAt: "2026-02-26T12:35:03.000Z",
|
||||
commandId: CommandId.make("cmd-stale-user-input-4"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.make("cmd-stale-user-input-4"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-stale-user-input"),
|
||||
activity: {
|
||||
id: EventId.make("activity-stale-user-input-failed"),
|
||||
tone: "error",
|
||||
kind: "provider.user-input.respond.failed",
|
||||
summary: "Provider user input response failed",
|
||||
payload: {
|
||||
requestId: "user-input-request-stale-1",
|
||||
detail:
|
||||
"Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: user-input-request-stale-1",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: "2026-02-26T12:35:03.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const threadRows = yield* sql<{
|
||||
readonly pendingUserInputCount: number;
|
||||
}>`
|
||||
SELECT pending_user_input_count AS "pendingUserInputCount"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-stale-user-input'
|
||||
`;
|
||||
assert.deepEqual(threadRows, [{ pendingUserInputCount: 0 }]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores non-stale provider approval response failures", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
ApprovalRequestId,
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationSessionStatus,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -69,6 +70,29 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
type ProjectorName =
|
||||
(typeof ORCHESTRATION_PROJECTOR_NAMES)[keyof typeof ORCHESTRATION_PROJECTOR_NAMES];
|
||||
|
||||
/**
|
||||
* Turn state to settle still-running turns with when their session leaves the
|
||||
* "running" status, or null while the session is (re)starting or running and
|
||||
* turns must stay unsettled.
|
||||
*/
|
||||
function settledTurnStateForSessionStatus(
|
||||
status: OrchestrationSessionStatus,
|
||||
): "completed" | "interrupted" | "error" | null {
|
||||
switch (status) {
|
||||
case "idle":
|
||||
case "ready":
|
||||
return "completed";
|
||||
case "error":
|
||||
return "error";
|
||||
case "interrupted":
|
||||
case "stopped":
|
||||
return "interrupted";
|
||||
case "starting":
|
||||
case "running":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface ProjectorDefinition {
|
||||
readonly name: ProjectorName;
|
||||
readonly apply: (
|
||||
@@ -141,7 +165,9 @@ function derivePendingUserInputCountFromActivities(
|
||||
activity.kind === "provider.user-input.respond.failed" &&
|
||||
detail !== null &&
|
||||
(detail.includes("stale pending user-input request") ||
|
||||
detail.includes("unknown pending user-input request"))
|
||||
detail.includes("unknown pending user-input request") ||
|
||||
detail.includes("unknown pending user input request") ||
|
||||
detail.includes("unknown pending codex user input request"))
|
||||
) {
|
||||
openRequestIds.delete(requestId);
|
||||
}
|
||||
@@ -999,9 +1025,57 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
case "thread.session-set": {
|
||||
const turnId = event.payload.session.activeTurnId;
|
||||
if (turnId === null || event.payload.session.status !== "running") {
|
||||
// Leaving the "running" session status is the turn-end signal:
|
||||
// settle still-running turns so their duration reflects the whole
|
||||
// turn rather than the last assistant message.
|
||||
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
|
||||
if (settledTurnState === null) {
|
||||
return;
|
||||
}
|
||||
const existingTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
existingTurns.filter((turn) => turn.turnId !== null && turn.state === "running"),
|
||||
(turn) =>
|
||||
turn.turnId === null
|
||||
? Effect.void
|
||||
: projectionTurnRepository.upsertByTurnId({
|
||||
...turn,
|
||||
turnId: turn.turnId,
|
||||
state: settledTurnState,
|
||||
// A running turn's completedAt can only hold a mid-turn
|
||||
// placeholder checkpoint timestamp — the session leaving
|
||||
// "running" is the authoritative turn end.
|
||||
completedAt: event.payload.session.updatedAt,
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// A new active turn supersedes any still-running turn on the same
|
||||
// thread — steering can open a new turn without the provider ever
|
||||
// completing the previous one.
|
||||
const otherRunningTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
otherRunningTurns.filter(
|
||||
(turn) => turn.turnId !== null && turn.turnId !== turnId && turn.state === "running",
|
||||
),
|
||||
(turn) =>
|
||||
turn.turnId === null
|
||||
? Effect.void
|
||||
: projectionTurnRepository.upsertByTurnId({
|
||||
...turn,
|
||||
turnId: turn.turnId,
|
||||
state: "completed",
|
||||
completedAt: event.payload.session.updatedAt,
|
||||
}),
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId,
|
||||
@@ -1080,6 +1154,19 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
if (event.payload.turnId === null || event.payload.role !== "assistant") {
|
||||
return;
|
||||
}
|
||||
// A completed assistant message only settles the turn once the
|
||||
// session is no longer running it — providers may emit several
|
||||
// assistant messages per turn (commentary between tool calls), and
|
||||
// the turn must stay unsettled until the provider reports turn end
|
||||
// (projected as thread.session-set leaving the "running" status).
|
||||
const session = yield* projectionThreadSessionRepository.getByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const turnStillRunning =
|
||||
Option.isSome(session) &&
|
||||
session.value.status === "running" &&
|
||||
session.value.activeTurnId === event.payload.turnId;
|
||||
const settlesTurn = !event.payload.streaming && !turnStillRunning;
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
@@ -1088,16 +1175,16 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
...existingTurn.value,
|
||||
assistantMessageId: event.payload.messageId,
|
||||
state: event.payload.streaming
|
||||
? existingTurn.value.state
|
||||
: existingTurn.value.state === "interrupted"
|
||||
state: settlesTurn
|
||||
? existingTurn.value.state === "interrupted"
|
||||
? "interrupted"
|
||||
: existingTurn.value.state === "error"
|
||||
? "error"
|
||||
: "completed",
|
||||
completedAt: event.payload.streaming
|
||||
? existingTurn.value.completedAt
|
||||
: (existingTurn.value.completedAt ?? event.payload.updatedAt),
|
||||
: "completed"
|
||||
: existingTurn.value.state,
|
||||
completedAt: settlesTurn
|
||||
? (existingTurn.value.completedAt ?? event.payload.updatedAt)
|
||||
: existingTurn.value.completedAt,
|
||||
startedAt: existingTurn.value.startedAt ?? event.payload.createdAt,
|
||||
requestedAt: existingTurn.value.requestedAt ?? event.payload.createdAt,
|
||||
});
|
||||
@@ -1110,10 +1197,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
sourceProposedPlanThreadId: null,
|
||||
sourceProposedPlanId: null,
|
||||
assistantMessageId: event.payload.messageId,
|
||||
state: event.payload.streaming ? "running" : "completed",
|
||||
state: settlesTurn ? "completed" : "running",
|
||||
requestedAt: event.payload.createdAt,
|
||||
startedAt: event.payload.createdAt,
|
||||
completedAt: event.payload.streaming ? null : event.payload.updatedAt,
|
||||
completedAt: settlesTurn ? event.payload.updatedAt : null,
|
||||
checkpointTurnCount: null,
|
||||
checkpointRef: null,
|
||||
checkpointStatus: null,
|
||||
@@ -1160,6 +1247,15 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
|
||||
case "thread.turn-diff-completed": {
|
||||
// Mid-turn diff updates produce placeholder checkpoints; record the
|
||||
// checkpoint, but don't settle a turn its session is still running.
|
||||
const session = yield* projectionThreadSessionRepository.getByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const turnStillRunning =
|
||||
Option.isSome(session) &&
|
||||
session.value.status === "running" &&
|
||||
session.value.activeTurnId === event.payload.turnId;
|
||||
const existingTurn = yield* projectionTurnRepository.getByTurnId({
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
@@ -1175,7 +1271,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
yield* projectionTurnRepository.upsertByTurnId({
|
||||
...existingTurn.value,
|
||||
assistantMessageId: event.payload.assistantMessageId,
|
||||
state: nextState,
|
||||
state: turnStillRunning ? existingTurn.value.state : nextState,
|
||||
checkpointTurnCount: event.payload.checkpointTurnCount,
|
||||
checkpointRef: event.payload.checkpointRef,
|
||||
checkpointStatus: event.payload.status,
|
||||
@@ -1193,7 +1289,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
sourceProposedPlanThreadId: null,
|
||||
sourceProposedPlanId: null,
|
||||
assistantMessageId: event.payload.assistantMessageId,
|
||||
state: nextState,
|
||||
state: turnStillRunning ? "running" : nextState,
|
||||
requestedAt: event.payload.completedAt,
|
||||
startedAt: event.payload.completedAt,
|
||||
completedAt: event.payload.completedAt,
|
||||
|
||||
@@ -1943,7 +1943,7 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(resolvedActivity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("surfaces stale provider user-input failures without faking user-input resolution", async () => {
|
||||
it("surfaces non-resumable provider user-input callbacks as stale failures", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
harness.respondToUserInput.mockImplementation(() =>
|
||||
@@ -1951,7 +1951,7 @@ describe("ProviderCommandReactor", () => {
|
||||
new ProviderAdapterRequestError({
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
method: "item/tool/respondToUserInput",
|
||||
detail: "Unknown pending user-input request: user-input-request-1",
|
||||
detail: "Unknown pending Codex user input request: user-input-request-1",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -141,9 +141,19 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
|
||||
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = findProviderAdapterRequestError(cause);
|
||||
if (error) {
|
||||
return error.detail.toLowerCase().includes("unknown pending user-input request");
|
||||
const detail = error.detail.toLowerCase();
|
||||
return (
|
||||
detail.includes("unknown pending user-input request") ||
|
||||
detail.includes("unknown pending user input request") ||
|
||||
detail.includes("unknown pending codex user input request")
|
||||
);
|
||||
}
|
||||
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
|
||||
const message = Cause.pretty(cause).toLowerCase();
|
||||
return (
|
||||
message.includes("unknown pending user-input request") ||
|
||||
message.includes("unknown pending user input request") ||
|
||||
message.includes("unknown pending codex user input request")
|
||||
);
|
||||
}
|
||||
|
||||
function stalePendingRequestDetail(
|
||||
|
||||
@@ -1117,39 +1117,39 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
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.make("cmd-session-set-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
Effect.andThen(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-create-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("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: ProviderDriverKind.make("codex"),
|
||||
@@ -1260,6 +1260,92 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId);
|
||||
});
|
||||
|
||||
it("accepts a conflicting turn.started for a pending turn start when the provider expects that turn", async () => {
|
||||
// Steering a running turn: the server requests a new turn while the old
|
||||
// one is still active, and providers like opencode open the new turn
|
||||
// without ever completing the superseded one. The new turn.started must
|
||||
// replace the active turn instead of being rejected as stale.
|
||||
const harness = await createHarness();
|
||||
const threadId = asThreadId("thread-1");
|
||||
const oldTurnId = asTurnId("turn-steered-over");
|
||||
const newTurnId = asTurnId("turn-from-steer");
|
||||
const createdAt = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
harness.setProviderSession({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
status: "running",
|
||||
runtimeMode: "approval-required",
|
||||
threadId,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
activeTurnId: oldTurnId,
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-steered-over"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt,
|
||||
threadId,
|
||||
turnId: oldTurnId,
|
||||
});
|
||||
await waitForThread(
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === oldTurnId,
|
||||
2_000,
|
||||
threadId,
|
||||
);
|
||||
|
||||
// The steer: a user-requested turn start while the old turn still runs.
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-steer"),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-steer"),
|
||||
role: "user",
|
||||
text: "actually, do 15 instead",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
// The provider session tracks the new turn before emitting turn.started
|
||||
// (sendTurn updates the session first).
|
||||
harness.setProviderSession({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
status: "running",
|
||||
runtimeMode: "approval-required",
|
||||
threadId,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
activeTurnId: newTurnId,
|
||||
});
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-from-steer"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
createdAt,
|
||||
threadId,
|
||||
turnId: newTurnId,
|
||||
});
|
||||
|
||||
const threadAfterSteer = await waitForThread(
|
||||
harness.readModel,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === newTurnId,
|
||||
2_000,
|
||||
threadId,
|
||||
);
|
||||
expect(threadAfterSteer.session?.activeTurnId).toBe(newTurnId);
|
||||
expect(threadAfterSteer.latestTurn?.turnId).toBe(newTurnId);
|
||||
expect(threadAfterSteer.latestTurn?.state).toBe("running");
|
||||
});
|
||||
|
||||
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");
|
||||
|
||||
@@ -1226,6 +1226,22 @@ const make = Effect.gen(function* () {
|
||||
activeTurnId !== null && eventTurnId !== undefined && !sameId(activeTurnId, eventTurnId);
|
||||
const missingTurnForActiveTurn = activeTurnId !== null && eventTurnId === undefined;
|
||||
|
||||
// A turn.started that conflicts with the active turn is legitimate when
|
||||
// the server itself has a turn start pending for this thread AND the
|
||||
// provider session already tracks the event's turn as its active turn:
|
||||
// steering a running turn makes some providers (e.g. opencode) open a
|
||||
// new turn without ever completing the superseded one. A stale
|
||||
// turn.started for some other turn id still gets rejected.
|
||||
const conflictingTurnStartIsPendingTurnStart =
|
||||
event.type === "turn.started" && conflictsWithActiveTurn
|
||||
? sameId(yield* getExpectedProviderTurnIdForThread(thread.id), eventTurnId) &&
|
||||
Option.isSome(
|
||||
yield* projectionTurnRepository.getPendingTurnStartByThreadId({
|
||||
threadId: thread.id,
|
||||
}),
|
||||
)
|
||||
: false;
|
||||
|
||||
const shouldApplyThreadLifecycle = (() => {
|
||||
if (!STRICT_PROVIDER_LIFECYCLE_GUARD) {
|
||||
return true;
|
||||
@@ -1237,7 +1253,7 @@ const make = Effect.gen(function* () {
|
||||
case "thread.started":
|
||||
return true;
|
||||
case "turn.started":
|
||||
return !conflictsWithActiveTurn;
|
||||
return !conflictsWithActiveTurn || conflictingTurnStartIsPendingTurnStart;
|
||||
case "turn.completed":
|
||||
if (conflictsWithActiveTurn || missingTurnForActiveTurn) {
|
||||
return false;
|
||||
|
||||
@@ -267,37 +267,76 @@ describe("orchestration projector", () => {
|
||||
),
|
||||
);
|
||||
|
||||
const afterRunning = await Effect.runPromise(
|
||||
projectEvent(
|
||||
afterCreate,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.session-set",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: startedAt,
|
||||
commandId: "cmd-running",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
session: {
|
||||
const settledAt = "2026-02-23T08:01:00.000Z";
|
||||
const [afterRunning, afterReady] = await Effect.runPromise(
|
||||
Effect.flatMap(
|
||||
projectEvent(
|
||||
afterCreate,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.session-set",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: startedAt,
|
||||
commandId: "cmd-running",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: "turn-1",
|
||||
lastError: null,
|
||||
updatedAt: startedAt,
|
||||
session: {
|
||||
threadId: "thread-1",
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: "turn-1",
|
||||
lastError: null,
|
||||
updatedAt: startedAt,
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
),
|
||||
(running) =>
|
||||
Effect.map(
|
||||
projectEvent(
|
||||
running,
|
||||
makeEvent({
|
||||
sequence: 3,
|
||||
type: "thread.session-set",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: settledAt,
|
||||
commandId: "cmd-ready",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
session: {
|
||||
threadId: "thread-1",
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: settledAt,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
(ready) => [running, ready] as const,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const thread = afterRunning.threads[0];
|
||||
expect(thread?.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(thread?.session?.status).toBe("running");
|
||||
|
||||
// Leaving the "running" session status settles the running turn with the
|
||||
// session timestamp as the turn end.
|
||||
const settledThread = afterReady.threads[0];
|
||||
expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
|
||||
expect(settledThread?.latestTurn?.state).toBe("completed");
|
||||
expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
|
||||
});
|
||||
|
||||
it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
|
||||
|
||||
@@ -38,6 +38,29 @@ function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error"
|
||||
return "completed" as const;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn state to settle a still-running latest turn with when its session
|
||||
* leaves the "running" status, or null while the session is (re)starting or
|
||||
* running and the turn must stay unsettled.
|
||||
*/
|
||||
function settledTurnStateForSessionStatus(
|
||||
status: OrchestrationSession["status"],
|
||||
): "completed" | "interrupted" | "error" | null {
|
||||
switch (status) {
|
||||
case "idle":
|
||||
case "ready":
|
||||
return "completed";
|
||||
case "error":
|
||||
return "error";
|
||||
case "interrupted":
|
||||
case "stopped":
|
||||
return "interrupted";
|
||||
case "starting":
|
||||
case "running":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function updateThread(
|
||||
threads: ReadonlyArray<OrchestrationThread>,
|
||||
threadId: ThreadId,
|
||||
@@ -438,6 +461,9 @@ export function projectEvent(
|
||||
"session",
|
||||
);
|
||||
|
||||
// Leaving the "running" session status is the turn-end signal: settle
|
||||
// a still-running latest turn so its duration reflects the whole turn.
|
||||
const settledTurnState = settledTurnStateForSessionStatus(session.status);
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
@@ -461,7 +487,18 @@ export function projectEvent(
|
||||
? thread.latestTurn.assistantMessageId
|
||||
: null,
|
||||
}
|
||||
: thread.latestTurn,
|
||||
: thread.latestTurn !== null &&
|
||||
thread.latestTurn.state === "running" &&
|
||||
settledTurnState !== null
|
||||
? {
|
||||
...thread.latestTurn,
|
||||
state: settledTurnState,
|
||||
// A running turn's completedAt can only hold a mid-turn
|
||||
// placeholder checkpoint timestamp — the session leaving
|
||||
// "running" is the authoritative turn end.
|
||||
completedAt: session.updatedAt,
|
||||
}
|
||||
: thread.latestTurn,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
@@ -544,24 +581,31 @@ export function projectEvent(
|
||||
.toSorted((left, right) => left.checkpointTurnCount - right.checkpointTurnCount)
|
||||
.slice(-MAX_THREAD_CHECKPOINTS);
|
||||
|
||||
// Mid-turn diff updates produce placeholder checkpoints; record the
|
||||
// checkpoint, but don't settle a turn its session is still running.
|
||||
const turnStillRunning =
|
||||
thread.session?.status === "running" && thread.session.activeTurnId === payload.turnId;
|
||||
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
checkpoints,
|
||||
latestTurn: {
|
||||
turnId: payload.turnId,
|
||||
state: checkpointStatusToLatestTurnState(payload.status),
|
||||
requestedAt:
|
||||
thread.latestTurn?.turnId === payload.turnId
|
||||
? thread.latestTurn.requestedAt
|
||||
: payload.completedAt,
|
||||
startedAt:
|
||||
thread.latestTurn?.turnId === payload.turnId
|
||||
? (thread.latestTurn.startedAt ?? payload.completedAt)
|
||||
: payload.completedAt,
|
||||
completedAt: payload.completedAt,
|
||||
assistantMessageId: payload.assistantMessageId,
|
||||
},
|
||||
latestTurn: turnStillRunning
|
||||
? thread.latestTurn
|
||||
: {
|
||||
turnId: payload.turnId,
|
||||
state: checkpointStatusToLatestTurnState(payload.status),
|
||||
requestedAt:
|
||||
thread.latestTurn?.turnId === payload.turnId
|
||||
? thread.latestTurn.requestedAt
|
||||
: payload.completedAt,
|
||||
startedAt:
|
||||
thread.latestTurn?.turnId === payload.turnId
|
||||
? (thread.latestTurn.startedAt ?? payload.completedAt)
|
||||
: payload.completedAt,
|
||||
completedAt: payload.completedAt,
|
||||
assistantMessageId: payload.assistantMessageId,
|
||||
},
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
|
||||
@@ -890,6 +890,73 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.takeUntil(
|
||||
adapter.streamEvents,
|
||||
(event) => event.type === "turn.completed",
|
||||
).pipe(Stream.runCollect, Effect.forkChild);
|
||||
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "run 5 commands",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
// Steer: a second sendTurn while the turn is still running continues
|
||||
// the same turn — the message is queued into the live agent loop.
|
||||
const steeredTurn = yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "actually run 15",
|
||||
attachments: [],
|
||||
});
|
||||
assert.equal(String(steeredTurn.turnId), String(turn.turnId));
|
||||
|
||||
harness.query.emit({
|
||||
type: "assistant",
|
||||
session_id: "sdk-session-steer",
|
||||
uuid: "assistant-steer-1",
|
||||
parent_tool_use_id: null,
|
||||
message: {
|
||||
id: "assistant-message-steer-1",
|
||||
content: [{ type: "text", text: "Adjusting to 15." }],
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
session_id: "sdk-session-steer",
|
||||
uuid: "result-steer-1",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
|
||||
const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed");
|
||||
|
||||
// One turn boundary for the whole run: the steer produced no
|
||||
// turn.completed/turn.started pair.
|
||||
assert.equal(turnStartedEvents.length, 1);
|
||||
assert.equal(String(turnStartedEvents[0]?.turnId), String(turn.turnId));
|
||||
assert.equal(turnCompletedEvents.length, 1);
|
||||
assert.equal(String(turnCompletedEvents[0]?.turnId), String(turn.turnId));
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("maps Claude reasoning deltas, streamed tool inputs, and tool results", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
type PermissionResult,
|
||||
type PermissionUpdate,
|
||||
type SDKMessage,
|
||||
type SDKControlGetContextUsageResponse,
|
||||
type SDKResultMessage,
|
||||
type SettingSource,
|
||||
type SDKUserMessage,
|
||||
@@ -29,6 +30,7 @@ import {
|
||||
type ProviderApprovalDecision,
|
||||
ProviderDriverKind,
|
||||
ProviderInstanceId,
|
||||
type ModelSelection,
|
||||
ProviderItemId,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderRuntimeTurnStatus,
|
||||
@@ -120,6 +122,13 @@ interface ClaudeResumeState {
|
||||
interface ClaudeTurnState {
|
||||
readonly turnId: TurnId;
|
||||
readonly startedAt: string;
|
||||
/**
|
||||
* True for turns auto-started by assistant output arriving without an
|
||||
* active turn (background agent/subagent responses between user prompts).
|
||||
* Synthetic turns are auto-closed by the next sendTurn; real turns are
|
||||
* steered instead (the queued message continues the same turn).
|
||||
*/
|
||||
readonly synthetic?: boolean;
|
||||
readonly items: Array<unknown>;
|
||||
readonly assistantTextBlocks: Map<number, AssistantTextBlockState>;
|
||||
readonly assistantTextBlockOrder: Array<AssistantTextBlockState>;
|
||||
@@ -159,6 +168,13 @@ interface ToolInFlight {
|
||||
readonly lastEmittedInputFingerprint?: string;
|
||||
}
|
||||
|
||||
interface ClaudeTaskState {
|
||||
readonly id: string;
|
||||
subject: string;
|
||||
status: PlanStep["status"];
|
||||
readonly blockedBy: Set<string>;
|
||||
}
|
||||
|
||||
interface ClaudeSessionContext {
|
||||
session: ProviderSession;
|
||||
readonly promptQueue: Queue.Queue<PromptQueueItem>;
|
||||
@@ -175,9 +191,11 @@ interface ClaudeSessionContext {
|
||||
items: Array<unknown>;
|
||||
}>;
|
||||
readonly inFlightTools: Map<number, ToolInFlight>;
|
||||
readonly claudeTasks: Map<string, ClaudeTaskState>;
|
||||
turnState: ClaudeTurnState | undefined;
|
||||
lastKnownContextWindow: number | undefined;
|
||||
lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;
|
||||
lastKnownTotalProcessedTokens: number | undefined;
|
||||
lastAssistantUuid: string | undefined;
|
||||
lastThreadStartedId: string | undefined;
|
||||
stopped: boolean;
|
||||
@@ -188,6 +206,7 @@ interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
|
||||
readonly setModel: (model?: string) => Promise<void>;
|
||||
readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;
|
||||
readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;
|
||||
readonly getContextUsage?: () => Promise<SDKControlGetContextUsageResponse>;
|
||||
readonly close: () => void;
|
||||
}
|
||||
|
||||
@@ -337,60 +356,220 @@ function maxClaudeContextWindowFromModelUsage(
|
||||
return maxContextWindow;
|
||||
}
|
||||
|
||||
function normalizeClaudeTokenUsage(
|
||||
function selectedClaudeContextWindow(
|
||||
modelSelection: ModelSelection | undefined,
|
||||
): number | undefined {
|
||||
switch (modelSelection?.model) {
|
||||
case "claude-opus-4-8":
|
||||
case "claude-opus-4-7":
|
||||
return 1_000_000;
|
||||
}
|
||||
|
||||
const optionValue = getModelSelectionStringOptionValue(modelSelection, "contextWindow");
|
||||
if (optionValue === "1m") {
|
||||
return 1_000_000;
|
||||
}
|
||||
if (optionValue === "200k") {
|
||||
return 200_000;
|
||||
}
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const hasContextWindowOption = getProviderOptionDescriptors({ caps }).some(
|
||||
(descriptor) => descriptor.type === "select" && descriptor.id === "contextWindow",
|
||||
);
|
||||
if (hasContextWindowOption) {
|
||||
return 200_000;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function finiteNonNegativeInteger(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) && value >= 0
|
||||
? Math.round(value)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function finitePositiveInteger(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) && value > 0
|
||||
? Math.round(value)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function claudeUsageInputTokens(usage: Record<string, unknown>): number {
|
||||
return (
|
||||
(finiteNonNegativeInteger(usage.input_tokens) ?? 0) +
|
||||
(finiteNonNegativeInteger(usage.cache_creation_input_tokens) ?? 0) +
|
||||
(finiteNonNegativeInteger(usage.cache_read_input_tokens) ?? 0)
|
||||
);
|
||||
}
|
||||
|
||||
function claudeUsageOutputTokens(usage: Record<string, unknown>): number {
|
||||
return finiteNonNegativeInteger(usage.output_tokens) ?? 0;
|
||||
}
|
||||
|
||||
function lastClaudeUsageIteration(
|
||||
value: Record<string, unknown>,
|
||||
): Record<string, unknown> | undefined {
|
||||
const iterations = Array.isArray(value.iterations) ? value.iterations : [];
|
||||
return iterations.findLast(
|
||||
(iteration): iteration is Record<string, unknown> =>
|
||||
iteration !== null && typeof iteration === "object" && !Array.isArray(iteration),
|
||||
);
|
||||
}
|
||||
|
||||
function claudeTotalProcessedTokens(value: unknown): number | undefined {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const usage = value as Record<string, unknown>;
|
||||
const explicitTotal = finiteNonNegativeInteger(usage.total_tokens);
|
||||
if (explicitTotal !== undefined && explicitTotal > 0) {
|
||||
return explicitTotal;
|
||||
}
|
||||
|
||||
const total = claudeUsageInputTokens(usage) + claudeUsageOutputTokens(usage);
|
||||
return total > 0 ? total : undefined;
|
||||
}
|
||||
|
||||
function makeClaudeTokenUsageSnapshot(input: {
|
||||
readonly activeTokens: number;
|
||||
readonly inputTokens?: number;
|
||||
readonly outputTokens?: number;
|
||||
readonly contextWindow?: number;
|
||||
readonly totalProcessedTokens?: number;
|
||||
readonly lastUsedTokens?: number;
|
||||
readonly compactsAutomatically?: boolean;
|
||||
}): ThreadTokenUsageSnapshot | undefined {
|
||||
const activeTokens = finiteNonNegativeInteger(input.activeTokens);
|
||||
if (activeTokens === undefined || activeTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const maxTokens = finitePositiveInteger(input.contextWindow);
|
||||
const usedTokens = maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens;
|
||||
const lastUsedTokens =
|
||||
finiteNonNegativeInteger(input.lastUsedTokens) ??
|
||||
(maxTokens !== undefined ? Math.min(activeTokens, maxTokens) : activeTokens);
|
||||
const totalProcessedTokens = finiteNonNegativeInteger(input.totalProcessedTokens);
|
||||
const inputTokens = finiteNonNegativeInteger(input.inputTokens);
|
||||
const outputTokens = finiteNonNegativeInteger(input.outputTokens);
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
lastUsedTokens,
|
||||
...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens
|
||||
? { totalProcessedTokens }
|
||||
: {}),
|
||||
...(inputTokens !== undefined && inputTokens > 0 ? { inputTokens } : {}),
|
||||
...(outputTokens !== undefined && outputTokens > 0 ? { outputTokens } : {}),
|
||||
...(maxTokens !== undefined ? { maxTokens } : {}),
|
||||
...(input.compactsAutomatically !== undefined
|
||||
? { compactsAutomatically: input.compactsAutomatically }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeClaudeActiveTokenUsage(
|
||||
value: unknown,
|
||||
contextWindow?: number,
|
||||
totalProcessedTokens?: number,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const usage = value as Record<string, unknown>;
|
||||
const inputTokens =
|
||||
(typeof usage.input_tokens === "number" && Number.isFinite(usage.input_tokens)
|
||||
? usage.input_tokens
|
||||
: 0) +
|
||||
(typeof usage.cache_creation_input_tokens === "number" &&
|
||||
Number.isFinite(usage.cache_creation_input_tokens)
|
||||
? usage.cache_creation_input_tokens
|
||||
: 0) +
|
||||
(typeof usage.cache_read_input_tokens === "number" &&
|
||||
Number.isFinite(usage.cache_read_input_tokens)
|
||||
? usage.cache_read_input_tokens
|
||||
: 0);
|
||||
const outputTokens =
|
||||
typeof usage.output_tokens === "number" && Number.isFinite(usage.output_tokens)
|
||||
? usage.output_tokens
|
||||
: 0;
|
||||
const derivedTotalProcessedTokens = inputTokens + outputTokens;
|
||||
const totalProcessedTokens =
|
||||
(typeof usage.total_tokens === "number" && Number.isFinite(usage.total_tokens)
|
||||
? usage.total_tokens
|
||||
: undefined) ?? (derivedTotalProcessedTokens > 0 ? derivedTotalProcessedTokens : undefined);
|
||||
if (totalProcessedTokens === undefined || totalProcessedTokens <= 0) {
|
||||
const activeUsage = lastClaudeUsageIteration(usage) ?? usage;
|
||||
const inputTokens = claudeUsageInputTokens(activeUsage);
|
||||
const outputTokens = claudeUsageOutputTokens(activeUsage);
|
||||
const activeTokens = claudeTotalProcessedTokens(activeUsage) ?? inputTokens + outputTokens;
|
||||
if (activeTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const maxTokens =
|
||||
typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
|
||||
? contextWindow
|
||||
: undefined;
|
||||
const usedTokens =
|
||||
maxTokens !== undefined ? Math.min(totalProcessedTokens, maxTokens) : totalProcessedTokens;
|
||||
return makeClaudeTokenUsageSnapshot({
|
||||
activeTokens,
|
||||
inputTokens,
|
||||
outputTokens,
|
||||
...(contextWindow !== undefined ? { contextWindow } : {}),
|
||||
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeClaudeContextUsageApiSnapshot(
|
||||
value: SDKControlGetContextUsageResponse,
|
||||
totalProcessedTokens?: number,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
return makeClaudeTokenUsageSnapshot({
|
||||
activeTokens: value.totalTokens,
|
||||
contextWindow: value.maxTokens,
|
||||
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
|
||||
compactsAutomatically: value.isAutoCompactEnabled,
|
||||
});
|
||||
}
|
||||
|
||||
function compactBoundaryTokenUsageSnapshot(
|
||||
message: Record<string, unknown>,
|
||||
contextWindow?: number,
|
||||
totalProcessedTokens?: number,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
const metadata = message.compact_metadata;
|
||||
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const compactMetadata = metadata as Record<string, unknown>;
|
||||
const postTokens = finiteNonNegativeInteger(compactMetadata.post_tokens);
|
||||
if (postTokens === undefined || postTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const preTokens = finiteNonNegativeInteger(compactMetadata.pre_tokens);
|
||||
return makeClaudeTokenUsageSnapshot({
|
||||
activeTokens: postTokens,
|
||||
...(preTokens !== undefined ? { lastUsedTokens: preTokens } : {}),
|
||||
...(contextWindow !== undefined ? { contextWindow } : {}),
|
||||
...(totalProcessedTokens !== undefined ? { totalProcessedTokens } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeClaudeTaskProgressTokenUsage(
|
||||
value: unknown,
|
||||
context: ClaudeSessionContext,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
const totalTokens = claudeTotalProcessedTokens(value);
|
||||
if (totalTokens === undefined || totalTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const lastUsedTokens = context.lastKnownTokenUsage?.usedTokens;
|
||||
const activeTokens =
|
||||
lastUsedTokens !== undefined ? Math.max(totalTokens, lastUsedTokens) : totalTokens;
|
||||
if (lastUsedTokens !== undefined && activeTokens === lastUsedTokens) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const usage = value as Record<string, unknown>;
|
||||
const snapshot = makeClaudeTokenUsageSnapshot({
|
||||
activeTokens,
|
||||
...(context.lastKnownContextWindow !== undefined
|
||||
? { contextWindow: context.lastKnownContextWindow }
|
||||
: {}),
|
||||
totalProcessedTokens: Math.max(
|
||||
totalTokens,
|
||||
context.lastKnownTotalProcessedTokens ?? totalTokens,
|
||||
),
|
||||
});
|
||||
if (!snapshot) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const toolUses = finiteNonNegativeInteger(usage.tool_uses);
|
||||
const durationMs = finiteNonNegativeInteger(usage.duration_ms);
|
||||
return {
|
||||
usedTokens,
|
||||
lastUsedTokens: usedTokens,
|
||||
...(totalProcessedTokens > usedTokens ? { totalProcessedTokens } : {}),
|
||||
...(inputTokens > 0 ? { inputTokens } : {}),
|
||||
...(outputTokens > 0 ? { outputTokens } : {}),
|
||||
...(maxTokens !== undefined ? { maxTokens } : {}),
|
||||
...(typeof usage.tool_uses === "number" && Number.isFinite(usage.tool_uses)
|
||||
? { toolUses: usage.tool_uses }
|
||||
: {}),
|
||||
...(typeof usage.duration_ms === "number" && Number.isFinite(usage.duration_ms)
|
||||
? { durationMs: usage.duration_ms }
|
||||
: {}),
|
||||
...snapshot,
|
||||
...(toolUses !== undefined ? { toolUses } : {}),
|
||||
...(durationMs !== undefined ? { durationMs } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -539,6 +718,140 @@ function extractPlanStepsFromTodoInput(input: Record<string, unknown>): PlanStep
|
||||
}));
|
||||
}
|
||||
|
||||
function isClaudeTaskTool(toolName: string): boolean {
|
||||
return toolName === "TaskCreate" || toolName === "TaskUpdate" || toolName === "TaskList";
|
||||
}
|
||||
|
||||
function normalizeClaudeTaskStatus(value: unknown): PlanStep["status"] {
|
||||
return value === "completed" ? "completed" : value === "in_progress" ? "inProgress" : "pending";
|
||||
}
|
||||
|
||||
function readString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function readStringArray(value: unknown): Array<string> {
|
||||
return Array.isArray(value)
|
||||
? value.filter((entry): entry is string => typeof entry === "string" && entry.length > 0)
|
||||
: [];
|
||||
}
|
||||
|
||||
function readClaudeToolUseResult(message: SDKMessage): Record<string, unknown> | undefined {
|
||||
if (message.type !== "user") {
|
||||
return undefined;
|
||||
}
|
||||
const result = (message as { readonly tool_use_result?: unknown }).tool_use_result;
|
||||
return result !== null && typeof result === "object" && !Array.isArray(result)
|
||||
? (result as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function readClaudeTaskFromResult(
|
||||
result: Record<string, unknown> | undefined,
|
||||
): Record<string, unknown> | undefined {
|
||||
const task = result?.task;
|
||||
return task !== null && typeof task === "object" && !Array.isArray(task)
|
||||
? (task as Record<string, unknown>)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function applyClaudeTaskToolResult(
|
||||
tasks: Map<string, ClaudeTaskState>,
|
||||
tool: ToolInFlight,
|
||||
result: Record<string, unknown> | undefined,
|
||||
): boolean {
|
||||
if (!isClaudeTaskTool(tool.toolName)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let changed = false;
|
||||
if (tool.toolName === "TaskList") {
|
||||
const resultTasks = result?.tasks;
|
||||
if (!Array.isArray(resultTasks)) {
|
||||
return false;
|
||||
}
|
||||
tasks.clear();
|
||||
for (const entry of resultTasks) {
|
||||
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
|
||||
continue;
|
||||
}
|
||||
const task = entry as Record<string, unknown>;
|
||||
const id = readString(task.id);
|
||||
const subject = readString(task.subject);
|
||||
if (!id || !subject) {
|
||||
continue;
|
||||
}
|
||||
tasks.set(id, {
|
||||
id,
|
||||
subject,
|
||||
status: normalizeClaudeTaskStatus(task.status),
|
||||
blockedBy: new Set(readStringArray(task.blockedBy)),
|
||||
});
|
||||
}
|
||||
return tasks.size > 0;
|
||||
}
|
||||
|
||||
if (tool.toolName === "TaskCreate") {
|
||||
const resultTask = readClaudeTaskFromResult(result);
|
||||
const id = readString(resultTask?.id);
|
||||
const subject = readString(resultTask?.subject) ?? readString(tool.input.subject);
|
||||
if (!id || !subject) {
|
||||
return false;
|
||||
}
|
||||
tasks.set(id, {
|
||||
id,
|
||||
subject,
|
||||
status: normalizeClaudeTaskStatus(tool.input.status),
|
||||
blockedBy: new Set(readStringArray(tool.input.blockedBy)),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
const taskId = readString(tool.input.taskId) ?? readString(result?.taskId);
|
||||
if (!taskId) {
|
||||
return false;
|
||||
}
|
||||
const task = tasks.get(taskId);
|
||||
if (!task) {
|
||||
return false;
|
||||
}
|
||||
const subject = readString(tool.input.subject);
|
||||
if (subject && task.subject !== subject) {
|
||||
task.subject = subject;
|
||||
changed = true;
|
||||
}
|
||||
if (typeof tool.input.status === "string") {
|
||||
const status = normalizeClaudeTaskStatus(tool.input.status);
|
||||
if (task.status !== status) {
|
||||
task.status = status;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (const dependency of readStringArray(tool.input.addBlockedBy)) {
|
||||
if (!task.blockedBy.has(dependency)) {
|
||||
task.blockedBy.add(dependency);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
for (const dependency of readStringArray(tool.input.removeBlockedBy)) {
|
||||
if (task.blockedBy.delete(dependency)) {
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
|
||||
function planStepsFromClaudeTasks(tasks: Map<string, ClaudeTaskState>): PlanStep[] {
|
||||
return Array.from(tasks.values()).map((task) => {
|
||||
const blockedBy = Array.from(task.blockedBy);
|
||||
const blockedSuffix = blockedBy.length > 0 ? ` (blocked by #${blockedBy.join(", #")})` : "";
|
||||
return {
|
||||
step: `${task.subject}${blockedSuffix}`,
|
||||
status: task.status,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {
|
||||
const commandValue = input.command ?? input.cmd;
|
||||
const command = typeof commandValue === "string" ? commandValue : undefined;
|
||||
@@ -1438,6 +1751,70 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
});
|
||||
|
||||
const emitThreadTokenUsage = Effect.fn("emitThreadTokenUsage")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
usage: ThreadTokenUsageSnapshot | undefined,
|
||||
options?: {
|
||||
readonly rawMethod?: string;
|
||||
readonly rawPayload?: unknown;
|
||||
},
|
||||
) {
|
||||
if (!usage) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.lastKnownTokenUsage = usage;
|
||||
context.lastKnownTotalProcessedTokens =
|
||||
usage.totalProcessedTokens ?? context.lastKnownTotalProcessedTokens;
|
||||
|
||||
const turnState = context.turnState;
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(turnState ? { turnId: turnState.turnId } : {}),
|
||||
payload: {
|
||||
usage,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context),
|
||||
...(options?.rawMethod || options?.rawPayload
|
||||
? {
|
||||
raw: {
|
||||
source: "claude.sdk.message" as const,
|
||||
...(options.rawMethod ? { method: options.rawMethod } : {}),
|
||||
payload: options.rawPayload,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
});
|
||||
|
||||
const queryCurrentContextUsage = Effect.fn("queryCurrentContextUsage")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
totalProcessedTokens?: number,
|
||||
) {
|
||||
if (!context.query.getContextUsage) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const usage = yield* Effect.promise(async () => {
|
||||
try {
|
||||
return await context.query.getContextUsage?.();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
if (!usage) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
context.lastKnownContextWindow = usage.maxTokens;
|
||||
return normalizeClaudeContextUsageApiSnapshot(usage, totalProcessedTokens);
|
||||
});
|
||||
|
||||
const emitProposedPlanCompleted = Effect.fn("emitProposedPlanCompleted")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
input: {
|
||||
@@ -1485,6 +1862,42 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
});
|
||||
|
||||
const emitClaudeTaskPlanUpdated = Effect.fn("emitClaudeTaskPlanUpdated")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
input: {
|
||||
readonly toolUseId: string;
|
||||
readonly rawMethod: string;
|
||||
readonly rawPayload: unknown;
|
||||
},
|
||||
) {
|
||||
const plan = planStepsFromClaudeTasks(context.claudeTasks);
|
||||
if (plan.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.plan.updated",
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
payload: {
|
||||
explanation: "Claude Tasks",
|
||||
plan,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context, {
|
||||
providerItemId: input.toolUseId,
|
||||
}),
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: input.rawMethod,
|
||||
payload: input.rawPayload,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const completeTurn = Effect.fn("completeTurn")(function* (
|
||||
context: ClaudeSessionContext,
|
||||
status: ProviderRuntimeTurnStatus,
|
||||
@@ -1496,51 +1909,77 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
context.lastKnownContextWindow = resultContextWindow;
|
||||
}
|
||||
|
||||
// The SDK result.usage contains *accumulated* totals across all API calls
|
||||
// (input_tokens, cache_read_input_tokens, etc. summed over every request).
|
||||
// This does NOT represent the current context window size.
|
||||
// Instead, use the last known context-window-accurate usage from task_progress
|
||||
// events and treat the accumulated total as totalProcessedTokens.
|
||||
const accumulatedSnapshot = normalizeClaudeTokenUsage(
|
||||
result?.usage,
|
||||
resultContextWindow ?? context.lastKnownContextWindow,
|
||||
);
|
||||
const accumulatedTotalProcessedTokens =
|
||||
accumulatedSnapshot?.totalProcessedTokens ?? accumulatedSnapshot?.usedTokens;
|
||||
const lastGoodUsage = context.lastKnownTokenUsage;
|
||||
const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
|
||||
const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage
|
||||
? {
|
||||
...lastGoodUsage,
|
||||
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
|
||||
? { maxTokens }
|
||||
: {}),
|
||||
...(typeof accumulatedTotalProcessedTokens === "number" &&
|
||||
Number.isFinite(accumulatedTotalProcessedTokens) &&
|
||||
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
|
||||
? {
|
||||
totalProcessedTokens: accumulatedTotalProcessedTokens,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: accumulatedSnapshot;
|
||||
const accumulatedTotalProcessedTokens = claudeTotalProcessedTokens(result?.usage);
|
||||
if (accumulatedTotalProcessedTokens !== undefined) {
|
||||
context.lastKnownTotalProcessedTokens = accumulatedTotalProcessedTokens;
|
||||
}
|
||||
|
||||
const contextUsageSnapshot = yield* queryCurrentContextUsage(
|
||||
context,
|
||||
accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,
|
||||
);
|
||||
const resultUsageRecord =
|
||||
result?.usage && typeof result.usage === "object" && !Array.isArray(result.usage)
|
||||
? (result.usage as Record<string, unknown>)
|
||||
: undefined;
|
||||
const hasResultUsageIteration =
|
||||
resultUsageRecord !== undefined && lastClaudeUsageIteration(resultUsageRecord) !== undefined;
|
||||
const resultHasActiveUsage =
|
||||
resultUsageRecord !== undefined &&
|
||||
(hasResultUsageIteration ||
|
||||
claudeUsageInputTokens(resultUsageRecord) + claudeUsageOutputTokens(resultUsageRecord) > 0);
|
||||
const resultTotalOnly =
|
||||
resultUsageRecord !== undefined &&
|
||||
!resultHasActiveUsage &&
|
||||
claudeTotalProcessedTokens(resultUsageRecord) !== undefined;
|
||||
const resultIterationSnapshot = resultUsageRecord
|
||||
? normalizeClaudeActiveTokenUsage(
|
||||
resultUsageRecord,
|
||||
maxTokens,
|
||||
accumulatedTotalProcessedTokens ?? context.lastKnownTotalProcessedTokens,
|
||||
)
|
||||
: undefined;
|
||||
const lastGoodUsage = context.lastKnownTokenUsage;
|
||||
const usageSnapshot: ThreadTokenUsageSnapshot | undefined =
|
||||
contextUsageSnapshot ??
|
||||
(resultTotalOnly && lastGoodUsage
|
||||
? {
|
||||
...lastGoodUsage,
|
||||
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
|
||||
? { maxTokens }
|
||||
: {}),
|
||||
...(typeof accumulatedTotalProcessedTokens === "number" &&
|
||||
Number.isFinite(accumulatedTotalProcessedTokens) &&
|
||||
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
|
||||
? {
|
||||
totalProcessedTokens: accumulatedTotalProcessedTokens,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: resultIterationSnapshot) ??
|
||||
(lastGoodUsage
|
||||
? {
|
||||
...lastGoodUsage,
|
||||
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
|
||||
? { maxTokens }
|
||||
: {}),
|
||||
...(typeof accumulatedTotalProcessedTokens === "number" &&
|
||||
Number.isFinite(accumulatedTotalProcessedTokens) &&
|
||||
accumulatedTotalProcessedTokens > lastGoodUsage.usedTokens
|
||||
? {
|
||||
totalProcessedTokens: accumulatedTotalProcessedTokens,
|
||||
}
|
||||
: {}),
|
||||
}
|
||||
: undefined);
|
||||
|
||||
const turnState = context.turnState;
|
||||
if (!turnState) {
|
||||
if (usageSnapshot) {
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: usageStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: usageStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
payload: {
|
||||
usage: usageSnapshot,
|
||||
},
|
||||
providerRefs: {},
|
||||
});
|
||||
}
|
||||
yield* emitThreadTokenUsage(context, usageSnapshot, {
|
||||
rawMethod: "claude/result",
|
||||
rawPayload: result ?? { status },
|
||||
});
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
@@ -1611,21 +2050,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
items: [...turnState.items],
|
||||
});
|
||||
|
||||
if (usageSnapshot) {
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: usageStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: usageStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId: turnState.turnId,
|
||||
payload: {
|
||||
usage: usageSnapshot,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context),
|
||||
});
|
||||
}
|
||||
yield* emitThreadTokenUsage(context, usageSnapshot, {
|
||||
rawMethod: "claude/result",
|
||||
rawPayload: result ?? { status },
|
||||
});
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
@@ -1670,6 +2098,23 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
|
||||
const { event } = message;
|
||||
|
||||
if (event.type === "message_delta") {
|
||||
if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const snapshot = normalizeClaudeActiveTokenUsage(
|
||||
event.usage,
|
||||
context.lastKnownContextWindow,
|
||||
context.lastKnownTotalProcessedTokens,
|
||||
);
|
||||
yield* emitThreadTokenUsage(context, snapshot, {
|
||||
rawMethod: "claude/stream_event/message_delta",
|
||||
rawPayload: message,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "content_block_delta") {
|
||||
if (
|
||||
(event.delta.type === "text_delta" || event.delta.type === "thinking_delta") &&
|
||||
@@ -1932,6 +2377,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
|
||||
const [index, tool] = toolEntry;
|
||||
const itemStatus = toolResult.isError ? "failed" : "completed";
|
||||
const toolUseResult = readClaudeToolUseResult(message);
|
||||
const toolData = {
|
||||
toolName: tool.toolName,
|
||||
input: tool.input,
|
||||
@@ -2016,6 +2462,17 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
},
|
||||
});
|
||||
|
||||
if (
|
||||
!toolResult.isError &&
|
||||
applyClaudeTaskToolResult(context.claudeTasks, tool, toolUseResult)
|
||||
) {
|
||||
yield* emitClaudeTaskPlanUpdated(context, {
|
||||
toolUseId: tool.itemId,
|
||||
rawMethod: "claude/user",
|
||||
rawPayload: message,
|
||||
});
|
||||
}
|
||||
|
||||
context.inFlightTools.delete(index);
|
||||
}
|
||||
});
|
||||
@@ -2036,6 +2493,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
context.turnState = {
|
||||
turnId,
|
||||
startedAt,
|
||||
synthetic: true,
|
||||
items: [],
|
||||
assistantTextBlocks: new Map(),
|
||||
assistantTextBlockOrder: [],
|
||||
@@ -2171,6 +2629,18 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
return;
|
||||
case "compact_boundary":
|
||||
yield* emitThreadTokenUsage(
|
||||
context,
|
||||
compactBoundaryTokenUsageSnapshot(
|
||||
message as unknown as Record<string, unknown>,
|
||||
context.lastKnownContextWindow,
|
||||
context.lastKnownTotalProcessedTokens,
|
||||
),
|
||||
{
|
||||
rawMethod: "claude/system/compact_boundary",
|
||||
rawPayload: message,
|
||||
},
|
||||
);
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "thread.state.changed",
|
||||
@@ -2229,25 +2699,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
return;
|
||||
case "task_progress":
|
||||
if (message.usage) {
|
||||
const normalizedUsage = normalizeClaudeTokenUsage(
|
||||
message.usage,
|
||||
context.lastKnownContextWindow,
|
||||
);
|
||||
if (normalizedUsage) {
|
||||
context.lastKnownTokenUsage = normalizedUsage;
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: usageStamp.eventId,
|
||||
createdAt: usageStamp.createdAt,
|
||||
type: "thread.token-usage.updated",
|
||||
payload: {
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
yield* emitThreadTokenUsage(
|
||||
context,
|
||||
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
|
||||
{
|
||||
rawMethod: "claude/system/task_progress",
|
||||
rawPayload: message,
|
||||
},
|
||||
);
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "task.progress",
|
||||
@@ -2261,25 +2720,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
return;
|
||||
case "task_notification":
|
||||
if (message.usage) {
|
||||
const normalizedUsage = normalizeClaudeTokenUsage(
|
||||
message.usage,
|
||||
context.lastKnownContextWindow,
|
||||
);
|
||||
if (normalizedUsage) {
|
||||
context.lastKnownTokenUsage = normalizedUsage;
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: usageStamp.eventId,
|
||||
createdAt: usageStamp.createdAt,
|
||||
type: "thread.token-usage.updated",
|
||||
payload: {
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
yield* emitThreadTokenUsage(
|
||||
context,
|
||||
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
|
||||
{
|
||||
rawMethod: "claude/system/task_notification",
|
||||
rawPayload: message,
|
||||
},
|
||||
);
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "task.completed",
|
||||
@@ -2669,6 +3117,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const pendingApprovals = new Map<ApprovalRequestId, PendingApproval>();
|
||||
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
|
||||
const inFlightTools = new Map<number, ToolInFlight>();
|
||||
const claudeTasks = new Map<string, ClaudeTaskState>();
|
||||
|
||||
const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);
|
||||
|
||||
@@ -2969,6 +3418,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const descriptors = getProviderOptionDescriptors({ caps });
|
||||
const apiModelId = modelSelection ? resolveClaudeApiModelId(modelSelection) : undefined;
|
||||
const initialContextWindow = selectedClaudeContextWindow(modelSelection);
|
||||
const rawEffort = getModelSelectionStringOptionValue(modelSelection, "effort");
|
||||
const effort = resolveClaudeEffort(caps, rawEffort) ?? null;
|
||||
const fastModeSupported = descriptors.some(
|
||||
@@ -3094,9 +3544,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
pendingUserInputs,
|
||||
turns: [],
|
||||
inFlightTools,
|
||||
claudeTasks,
|
||||
turnState: undefined,
|
||||
lastKnownContextWindow: undefined,
|
||||
lastKnownContextWindow: initialContextWindow,
|
||||
lastKnownTokenUsage: undefined,
|
||||
lastKnownTotalProcessedTokens: undefined,
|
||||
lastAssistantUuid: resumeState?.resumeSessionAt,
|
||||
lastThreadStartedId: undefined,
|
||||
stopped: false,
|
||||
@@ -3185,9 +3637,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
? input.modelSelection
|
||||
: undefined;
|
||||
|
||||
if (context.turnState) {
|
||||
// Auto-close a stale synthetic turn (from background agent responses
|
||||
// between user prompts) to prevent blocking the user's next turn.
|
||||
// A sendTurn while a real turn is running is a steer: the message is
|
||||
// queued into the live SDK agent loop and the work continues as the same
|
||||
// turn — no synthetic turn boundary. Stale synthetic turns (from
|
||||
// background agent responses between user prompts) are auto-closed
|
||||
// instead, so they don't block the user's next turn.
|
||||
const steeringTurnState =
|
||||
context.turnState && context.turnState.synthetic !== true ? context.turnState : null;
|
||||
if (context.turnState && steeringTurnState === null) {
|
||||
yield* completeTurn(context, "completed");
|
||||
}
|
||||
|
||||
@@ -3222,37 +3679,39 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
});
|
||||
}
|
||||
|
||||
const turnId = TurnId.make(yield* randomUUIDv4);
|
||||
const turnState: ClaudeTurnState = {
|
||||
turnId,
|
||||
startedAt: yield* nowIso,
|
||||
items: [],
|
||||
assistantTextBlocks: new Map(),
|
||||
assistantTextBlockOrder: [],
|
||||
capturedProposedPlanKeys: new Set(),
|
||||
nextSyntheticAssistantBlockIndex: -1,
|
||||
};
|
||||
const turnId = steeringTurnState?.turnId ?? TurnId.make(yield* randomUUIDv4);
|
||||
if (steeringTurnState === null) {
|
||||
const turnState: ClaudeTurnState = {
|
||||
turnId,
|
||||
startedAt: yield* nowIso,
|
||||
items: [],
|
||||
assistantTextBlocks: new Map(),
|
||||
assistantTextBlockOrder: [],
|
||||
capturedProposedPlanKeys: new Set(),
|
||||
nextSyntheticAssistantBlockIndex: -1,
|
||||
};
|
||||
|
||||
const updatedAt = yield* nowIso;
|
||||
context.turnState = turnState;
|
||||
context.session = {
|
||||
...context.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt,
|
||||
};
|
||||
const updatedAt = yield* nowIso;
|
||||
context.turnState = turnState;
|
||||
context.session = {
|
||||
...context.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt,
|
||||
};
|
||||
|
||||
const turnStartedStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
eventId: turnStartedStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: turnStartedStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId,
|
||||
payload: modelSelection?.model ? { model: modelSelection.model } : {},
|
||||
providerRefs: {},
|
||||
});
|
||||
const turnStartedStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
eventId: turnStartedStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: turnStartedStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId,
|
||||
payload: modelSelection?.model ? { model: modelSelection.model } : {},
|
||||
providerRefs: {},
|
||||
});
|
||||
}
|
||||
|
||||
const message = yield* buildUserMessageEffect(input, {
|
||||
fileSystem,
|
||||
|
||||
@@ -108,14 +108,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
@@ -142,14 +134,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
}),
|
||||
buildSelectOptionDescriptor({
|
||||
id: "contextWindow",
|
||||
label: "Context Window",
|
||||
options: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
},
|
||||
|
||||
@@ -271,7 +271,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
|
||||
{ id: "fastMode", value: true },
|
||||
{ id: "serviceTier", value: "priority" },
|
||||
]),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
@@ -281,7 +281,7 @@ validationLayer("CodexAdapterLive validation", (it) => {
|
||||
cwd: process.cwd(),
|
||||
model: "gpt-5.3-codex",
|
||||
providerInstanceId: ProviderInstanceId.make("codex"),
|
||||
serviceTier: "fast",
|
||||
serviceTier: "priority",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
@@ -344,7 +344,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
input: "hello",
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.3-codex", [
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
{ id: "serviceTier", value: "priority" },
|
||||
]),
|
||||
attachments: [],
|
||||
}),
|
||||
@@ -354,7 +354,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
input: "hello",
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "high",
|
||||
serviceTier: "fast",
|
||||
serviceTier: "priority",
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -398,7 +398,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
"gpt-5.3-codex",
|
||||
[
|
||||
{ id: "reasoningEffort", value: "high" },
|
||||
{ id: "fastMode", value: true },
|
||||
{ id: "serviceTier", value: "flex" },
|
||||
],
|
||||
),
|
||||
attachments: [],
|
||||
@@ -409,7 +409,7 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
input: "hello",
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "high",
|
||||
serviceTier: "fast",
|
||||
serviceTier: "flex",
|
||||
});
|
||||
}).pipe(Effect.provide(customLayer));
|
||||
});
|
||||
|
||||
@@ -37,10 +37,8 @@ import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
import * as CodexErrors from "effect-codex-app-server/errors";
|
||||
import * as EffectCodexSchema from "effect-codex-app-server/schema";
|
||||
|
||||
import {
|
||||
getModelSelectionBooleanOptionValue,
|
||||
getModelSelectionStringOptionValue,
|
||||
} from "@t3tools/shared/model";
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
import { getCodexServiceTierOptionValue } from "../../codexModelOptions.ts";
|
||||
|
||||
import {
|
||||
ProviderAdapterRequestError,
|
||||
@@ -1380,6 +1378,10 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
yield* Effect.suspend(() => stopSessionInternal(existing));
|
||||
}
|
||||
|
||||
const serviceTier =
|
||||
input.modelSelection?.instanceId === boundInstanceId
|
||||
? getCodexServiceTierOptionValue(input.modelSelection)
|
||||
: undefined;
|
||||
const runtimeInput: CodexSessionRuntimeOptions = {
|
||||
threadId: input.threadId,
|
||||
providerInstanceId: boundInstanceId,
|
||||
@@ -1394,10 +1396,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
...(input.modelSelection?.instanceId === boundInstanceId
|
||||
? { model: input.modelSelection.model }
|
||||
: {}),
|
||||
...(input.modelSelection?.instanceId === boundInstanceId &&
|
||||
getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode") === true
|
||||
? { serviceTier: "fast" }
|
||||
: {}),
|
||||
...(serviceTier ? { serviceTier } : {}),
|
||||
};
|
||||
const sessionScope = yield* Scope.make("sequential");
|
||||
let sessionScopeTransferred = false;
|
||||
@@ -1513,9 +1512,9 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
input.modelSelection?.instanceId === boundInstanceId
|
||||
? getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort")
|
||||
: undefined;
|
||||
const fastMode =
|
||||
const serviceTier =
|
||||
input.modelSelection?.instanceId === boundInstanceId
|
||||
? getModelSelectionBooleanOptionValue(input.modelSelection, "fastMode")
|
||||
? getCodexServiceTierOptionValue(input.modelSelection)
|
||||
: undefined;
|
||||
return yield* session.runtime
|
||||
.sendTurn({
|
||||
@@ -1528,7 +1527,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
effort: reasoningEffort as EffectCodexSchema.V2TurnStartParams__ReasoningEffort,
|
||||
}
|
||||
: {}),
|
||||
...(fastMode === true ? { serviceTier: "fast" } : {}),
|
||||
...(serviceTier ? { serviceTier } : {}),
|
||||
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
|
||||
...(codexAttachments.length > 0 ? { attachments: codexAttachments } : {}),
|
||||
})
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { assert, it } from "@effect/vitest";
|
||||
|
||||
import { mapCodexModelCapabilities } from "./CodexProvider.ts";
|
||||
|
||||
it("maps current Codex model capability fields", () => {
|
||||
const capabilities = mapCodexModelCapabilities({
|
||||
additionalSpeedTiers: [],
|
||||
defaultReasoningEffort: "super-high",
|
||||
description: "Test model",
|
||||
displayName: "GPT Test",
|
||||
hidden: false,
|
||||
id: "gpt-test",
|
||||
isDefault: true,
|
||||
model: "gpt-test",
|
||||
defaultServiceTier: "flex",
|
||||
serviceTiers: [
|
||||
{
|
||||
id: "priority",
|
||||
name: "Fast",
|
||||
description: "Lower latency responses.",
|
||||
},
|
||||
{
|
||||
id: "flex",
|
||||
name: "Flex",
|
||||
description: "Lower-cost asynchronous routing.",
|
||||
},
|
||||
],
|
||||
supportedReasoningEfforts: [
|
||||
{
|
||||
description: "Maximum reasoning",
|
||||
reasoningEffort: "super-high",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(capabilities.optionDescriptors, [
|
||||
{
|
||||
id: "reasoningEffort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
options: [{ id: "super-high", label: "super-high", isDefault: true }],
|
||||
currentValue: "super-high",
|
||||
},
|
||||
{
|
||||
id: "serviceTier",
|
||||
label: "Service Tier",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "default", label: "Standard" },
|
||||
{
|
||||
id: "priority",
|
||||
label: "Fast",
|
||||
description: "Lower latency responses.",
|
||||
},
|
||||
{
|
||||
id: "flex",
|
||||
label: "Flex",
|
||||
description: "Lower-cost asynchronous routing.",
|
||||
isDefault: true,
|
||||
},
|
||||
],
|
||||
currentValue: "flex",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("uses standard routing when the catalog has no default service tier", () => {
|
||||
const capabilities = mapCodexModelCapabilities({
|
||||
additionalSpeedTiers: ["fast"],
|
||||
defaultReasoningEffort: "medium",
|
||||
defaultServiceTier: null,
|
||||
description: "Test model",
|
||||
displayName: "GPT Test",
|
||||
hidden: false,
|
||||
id: "gpt-test",
|
||||
isDefault: true,
|
||||
model: "gpt-test",
|
||||
serviceTiers: [
|
||||
{
|
||||
id: "priority",
|
||||
name: "Fast",
|
||||
description: "1.5x speed, increased usage",
|
||||
},
|
||||
],
|
||||
supportedReasoningEfforts: [],
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(capabilities.optionDescriptors, [
|
||||
{
|
||||
id: "serviceTier",
|
||||
label: "Service Tier",
|
||||
type: "select",
|
||||
options: [
|
||||
{ id: "default", label: "Standard", isDefault: true },
|
||||
{
|
||||
id: "priority",
|
||||
label: "Fast",
|
||||
description: "1.5x speed, increased usage",
|
||||
},
|
||||
],
|
||||
currentValue: "default",
|
||||
},
|
||||
]);
|
||||
});
|
||||
@@ -17,6 +17,7 @@ import type {
|
||||
ServerProvider,
|
||||
ServerProviderState,
|
||||
ModelCapabilities,
|
||||
ProviderOptionDescriptor,
|
||||
ServerProviderModel,
|
||||
ServerProviderSkill,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -44,7 +45,7 @@ export interface CodexAppServerProviderSnapshot {
|
||||
readonly skills: ReadonlyArray<ServerProviderSkill>;
|
||||
}
|
||||
|
||||
const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__ReasoningEffort, string> = {
|
||||
const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
|
||||
none: "None",
|
||||
minimal: "Minimal",
|
||||
low: "Low",
|
||||
@@ -53,6 +54,12 @@ const REASONING_EFFORT_LABELS: Record<CodexSchema.V2ModelListResponse__Reasoning
|
||||
xhigh: "Extra High",
|
||||
};
|
||||
|
||||
const DEFAULT_SERVICE_TIER_ID = "default";
|
||||
|
||||
function reasoningEffortLabel(reasoningEffort: string): string {
|
||||
return REASONING_EFFORT_LABELS[reasoningEffort] ?? reasoningEffort;
|
||||
}
|
||||
|
||||
function codexAccountAuthLabel(account: CodexSchema.V2GetAccountResponse["account"]) {
|
||||
if (!account) return undefined;
|
||||
if (account.type === "apiKey") return "OpenAI API Key";
|
||||
@@ -93,46 +100,71 @@ function codexAccountEmail(account: CodexSchema.V2GetAccountResponse["account"])
|
||||
return account.email;
|
||||
}
|
||||
|
||||
function mapCodexModelCapabilities(
|
||||
export function mapCodexModelCapabilities(
|
||||
model: CodexSchema.V2ModelListResponse__Model,
|
||||
): ModelCapabilities {
|
||||
const reasoningOptions = model.supportedReasoningEfforts.map(({ reasoningEffort }) =>
|
||||
reasoningEffort === model.defaultReasoningEffort
|
||||
? {
|
||||
id: reasoningEffort,
|
||||
label: REASONING_EFFORT_LABELS[reasoningEffort],
|
||||
label: reasoningEffortLabel(reasoningEffort),
|
||||
isDefault: true,
|
||||
}
|
||||
: {
|
||||
id: reasoningEffort,
|
||||
label: REASONING_EFFORT_LABELS[reasoningEffort],
|
||||
label: reasoningEffortLabel(reasoningEffort),
|
||||
},
|
||||
);
|
||||
const defaultReasoning = reasoningOptions.find((option) => option.isDefault)?.id;
|
||||
const supportsFastMode = (model.additionalSpeedTiers ?? []).includes("fast");
|
||||
const serviceTiers =
|
||||
model.serviceTiers && model.serviceTiers.length > 0
|
||||
? model.serviceTiers
|
||||
: (model.additionalSpeedTiers ?? []).map((id) => ({
|
||||
id,
|
||||
name: id === "fast" ? "Fast" : id,
|
||||
description: "",
|
||||
}));
|
||||
const catalogDefaultServiceTier = serviceTiers.some(
|
||||
(tier) => tier.id === model.defaultServiceTier,
|
||||
)
|
||||
? model.defaultServiceTier
|
||||
: null;
|
||||
const defaultServiceTier = catalogDefaultServiceTier ?? DEFAULT_SERVICE_TIER_ID;
|
||||
const optionDescriptors: ProviderOptionDescriptor[] = [];
|
||||
|
||||
if (reasoningOptions.length > 0) {
|
||||
optionDescriptors.push({
|
||||
id: "reasoningEffort",
|
||||
label: "Reasoning",
|
||||
type: "select",
|
||||
options: reasoningOptions,
|
||||
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
|
||||
});
|
||||
}
|
||||
if (serviceTiers.length > 0) {
|
||||
optionDescriptors.push({
|
||||
id: "serviceTier",
|
||||
label: "Service Tier",
|
||||
type: "select",
|
||||
options: [
|
||||
{
|
||||
id: DEFAULT_SERVICE_TIER_ID,
|
||||
label: "Standard",
|
||||
...(defaultServiceTier === DEFAULT_SERVICE_TIER_ID ? { isDefault: true } : {}),
|
||||
},
|
||||
...serviceTiers.map((tier) => ({
|
||||
id: tier.id,
|
||||
label: tier.name,
|
||||
...(tier.description ? { description: tier.description } : {}),
|
||||
...(defaultServiceTier === tier.id ? { isDefault: true } : {}),
|
||||
})),
|
||||
],
|
||||
currentValue: defaultServiceTier,
|
||||
});
|
||||
}
|
||||
|
||||
return createModelCapabilities({
|
||||
optionDescriptors: [
|
||||
...(reasoningOptions.length > 0
|
||||
? [
|
||||
{
|
||||
id: "reasoningEffort",
|
||||
label: "Reasoning",
|
||||
type: "select" as const,
|
||||
options: reasoningOptions,
|
||||
...(defaultReasoning ? { currentValue: defaultReasoning } : {}),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...(supportsFastMode
|
||||
? [
|
||||
{
|
||||
id: "fastMode",
|
||||
label: "Fast Mode",
|
||||
type: "boolean" as const,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
optionDescriptors,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
|
||||
import {
|
||||
@@ -232,6 +233,82 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
const settings = yield* ServerSettingsService;
|
||||
const threadId = ThreadId.make("cursor-steer-thread");
|
||||
|
||||
// Keep the first prompt in flight long enough for the steer to land.
|
||||
const wrapperPath = yield* Effect.promise(() =>
|
||||
makeMockAgentWrapper({ T3_ACP_PROMPT_DELAY_MS: "1500" }),
|
||||
);
|
||||
yield* settings.updateSettings({ providers: { cursor: { binaryPath: wrapperPath } } });
|
||||
|
||||
const runtimeEventsFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.threadId === threadId),
|
||||
Stream.takeUntil((event) => event.type === "turn.completed"),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("cursor"),
|
||||
cwd: process.cwd(),
|
||||
runtimeMode: "full-access",
|
||||
modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" },
|
||||
});
|
||||
|
||||
const firstTurnFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "run 5 commands",
|
||||
attachments: [],
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
|
||||
// Poll until the first prompt is in flight — sendTurn binds the active
|
||||
// turn id before prompting. The mock agent runs on the real clock, so
|
||||
// each TestClock.adjust just provides the scheduler hops for its stdio
|
||||
// responses to land.
|
||||
yield* Effect.gen(function* () {
|
||||
for (let attempt = 0; attempt < 200; attempt += 1) {
|
||||
const sessions = yield* adapter.listSessions();
|
||||
const session = sessions.find((entry) => entry.threadId === threadId);
|
||||
if (session?.activeTurnId !== undefined) {
|
||||
return;
|
||||
}
|
||||
yield* TestClock.adjust("10 millis");
|
||||
}
|
||||
throw new Error("Timed out waiting for the first prompt to be in flight.");
|
||||
});
|
||||
|
||||
// Steer: a second sendTurn while the first prompt is still in flight
|
||||
// continues the same turn.
|
||||
const steeredTurn = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "actually run 15",
|
||||
attachments: [],
|
||||
});
|
||||
const firstTurn = yield* Fiber.join(firstTurnFiber);
|
||||
assert.equal(String(steeredTurn.turnId), String(firstTurn.turnId));
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const turnStartedEvents = runtimeEvents.filter((event) => event.type === "turn.started");
|
||||
const turnCompletedEvents = runtimeEvents.filter((event) => event.type === "turn.completed");
|
||||
|
||||
// One turn boundary for the whole run: the superseded first prompt
|
||||
// resolving must not settle the merged turn.
|
||||
assert.equal(turnStartedEvents.length, 1);
|
||||
assert.equal(String(turnStartedEvents[0]?.turnId), String(firstTurn.turnId));
|
||||
assert.equal(turnCompletedEvents.length, 1);
|
||||
assert.equal(String(turnCompletedEvents[0]?.turnId), String(firstTurn.turnId));
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("closes the ACP child process when a session stops", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CursorAdapter;
|
||||
|
||||
@@ -132,6 +132,10 @@ interface CursorSessionContext {
|
||||
readonly turns: Array<{ id: TurnId; items: Array<unknown> }>;
|
||||
lastPlanFingerprint: string | undefined;
|
||||
activeTurnId: TurnId | undefined;
|
||||
/** Number of sendTurn prompts currently in flight or being prepared.
|
||||
* >0 means a turn is actively running, so a new sendTurn is a steer that
|
||||
* continues it, and only the last remaining prompt settles the turn. */
|
||||
promptsInFlight: number;
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
@@ -754,6 +758,7 @@ export function makeCursorAdapter(
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
promptsInFlight: 0,
|
||||
stopped: false,
|
||||
};
|
||||
|
||||
@@ -882,121 +887,152 @@ export function makeCursorAdapter(
|
||||
const sendTurn: CursorAdapterShape["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
const turnId = TurnId.make(yield* randomUUIDv4);
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
|
||||
const model = turnModelSelection?.model ?? ctx.session.model;
|
||||
const resolvedModel = resolveCursorAcpBaseModelId(model);
|
||||
yield* applyRequestedSessionConfiguration({
|
||||
runtime: ctx.acp,
|
||||
runtimeMode: ctx.session.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
modelSelection:
|
||||
model === undefined
|
||||
? undefined
|
||||
: {
|
||||
model,
|
||||
options: turnModelSelection?.options,
|
||||
},
|
||||
mapError: ({ cause, method }) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
|
||||
});
|
||||
ctx.activeTurnId = turnId;
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
// A sendTurn while a prompt is in flight is a steer: the agent folds
|
||||
// the new prompt into the ongoing work, so the active turn id is
|
||||
// reused instead of opening a new turn.
|
||||
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
|
||||
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
|
||||
// Count this prompt immediately so a superseded in-flight prompt
|
||||
// resolving from here on does not settle the turn; the matching
|
||||
// decrement is the `ensuring` below.
|
||||
ctx.promptsInFlight += 1;
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: { model: resolvedModel },
|
||||
});
|
||||
return yield* Effect.gen(function* () {
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === boundInstanceId ? input.modelSelection : undefined;
|
||||
const model = turnModelSelection?.model ?? ctx.session.model;
|
||||
const resolvedModel = resolveCursorAcpBaseModelId(model);
|
||||
yield* applyRequestedSessionConfiguration({
|
||||
runtime: ctx.acp,
|
||||
runtimeMode: ctx.session.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
modelSelection:
|
||||
model === undefined
|
||||
? undefined
|
||||
: {
|
||||
model,
|
||||
options: turnModelSelection?.options,
|
||||
},
|
||||
mapError: ({ cause, method }) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, method, cause),
|
||||
});
|
||||
ctx.activeTurnId = turnId;
|
||||
if (steeringTurnId === undefined) {
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
};
|
||||
|
||||
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
|
||||
if (input.input?.trim()) {
|
||||
promptParts.push({ type: "text", text: input.input.trim() });
|
||||
}
|
||||
if (input.attachments && input.attachments.length > 0) {
|
||||
for (const attachment of input.attachments) {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
promptParts.push({
|
||||
type: "image",
|
||||
data: Buffer.from(bytes).toString("base64"),
|
||||
mimeType: attachment.mimeType,
|
||||
if (steeringTurnId === undefined) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: { model: resolvedModel },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (promptParts.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
}
|
||||
const promptParts: Array<EffectAcpSchema.ContentBlock> = [];
|
||||
if (input.input?.trim()) {
|
||||
promptParts.push({ type: "text", text: input.input.trim() });
|
||||
}
|
||||
if (input.attachments && input.attachments.length > 0) {
|
||||
for (const attachment of input.attachments) {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
promptParts.push({
|
||||
type: "image",
|
||||
data: Buffer.from(bytes).toString("base64"),
|
||||
mimeType: attachment.mimeType,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const result = yield* ctx.acp
|
||||
.prompt({
|
||||
prompt: promptParts,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
),
|
||||
);
|
||||
if (promptParts.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
}
|
||||
|
||||
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
model: resolvedModel,
|
||||
};
|
||||
const result = yield* ctx.acp
|
||||
.prompt({
|
||||
prompt: promptParts,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
),
|
||||
);
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
const turnRecord = ctx.turns.find((turn) => turn.id === turnId);
|
||||
if (turnRecord) {
|
||||
turnRecord.items.push({ prompt: promptParts, result });
|
||||
} else {
|
||||
ctx.turns.push({ id: turnId, items: [{ prompt: promptParts, result }] });
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
model: resolvedModel,
|
||||
};
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
// Only the last remaining prompt settles the turn — a steer-
|
||||
// superseded prompt resolving (usually cancelled) while another is
|
||||
// in flight or pending must leave the merged turn running.
|
||||
if (ctx.promptsInFlight === 1) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const interruptTurn: CursorAdapterShape["interruptTurn"] = (threadId) =>
|
||||
|
||||
@@ -107,6 +107,10 @@ interface GrokSessionContext {
|
||||
turns: Array<{ id: TurnId; items: Array<unknown> }>;
|
||||
lastPlanFingerprint: string | undefined;
|
||||
activeTurnId: TurnId | undefined;
|
||||
/** Number of sendTurn prompts currently in flight or being prepared.
|
||||
* >0 means a turn is actively running, so a new sendTurn is a steer that
|
||||
* continues it, and only the last remaining prompt settles the turn. */
|
||||
promptsInFlight: number;
|
||||
currentModelId: string | undefined;
|
||||
stopped: boolean;
|
||||
}
|
||||
@@ -555,6 +559,7 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
turns: [],
|
||||
lastPlanFingerprint: undefined,
|
||||
activeTurnId: undefined,
|
||||
promptsInFlight: 0,
|
||||
currentModelId: boundModelId,
|
||||
stopped: false,
|
||||
};
|
||||
@@ -664,150 +669,199 @@ export function makeGrokAdapter(grokSettings: GrokSettings, options?: GrokAdapte
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
const turnId = TurnId.make(yield* randomUUIDv4);
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === boundInstanceId
|
||||
? input.modelSelection
|
||||
: undefined;
|
||||
const requestedTurnModelId = turnModelSelection?.model
|
||||
? resolveGrokAcpBaseModelId(turnModelSelection.model)
|
||||
: undefined;
|
||||
const currentModelId = yield* applyGrokAcpModelSelection({
|
||||
runtime: ctx.acp,
|
||||
currentModelId: ctx.currentModelId,
|
||||
requestedModelId: requestedTurnModelId,
|
||||
mapError: (cause) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
|
||||
});
|
||||
// A sendTurn while a prompt is in flight is a steer: the agent
|
||||
// folds the new prompt into the ongoing work, so the active turn
|
||||
// id is reused instead of opening a new turn.
|
||||
const steeringTurnId = ctx.promptsInFlight > 0 ? ctx.activeTurnId : undefined;
|
||||
const turnId = steeringTurnId ?? TurnId.make(yield* randomUUIDv4);
|
||||
// Count this prompt immediately so a superseded in-flight prompt
|
||||
// resolving from here on does not settle the turn; decremented on
|
||||
// preparation failure here, and after the prompt below otherwise.
|
||||
ctx.promptsInFlight += 1;
|
||||
|
||||
const text = input.input?.trim();
|
||||
const imagePromptParts = yield* Effect.forEach(input.attachments ?? [], (attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
return yield* Effect.gen(function* () {
|
||||
const turnModelSelection =
|
||||
input.modelSelection?.instanceId === boundInstanceId
|
||||
? input.modelSelection
|
||||
: undefined;
|
||||
const requestedTurnModelId = turnModelSelection?.model
|
||||
? resolveGrokAcpBaseModelId(turnModelSelection.model)
|
||||
: undefined;
|
||||
const currentModelId = yield* applyGrokAcpModelSelection({
|
||||
runtime: ctx.acp,
|
||||
currentModelId: ctx.currentModelId,
|
||||
requestedModelId: requestedTurnModelId,
|
||||
mapError: (cause) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/set_model", cause),
|
||||
});
|
||||
|
||||
const text = input.input?.trim();
|
||||
const imagePromptParts = yield* Effect.forEach(
|
||||
input.attachments ?? [],
|
||||
(attachment) =>
|
||||
Effect.gen(function* () {
|
||||
const attachmentPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!attachmentPath) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
type: "image",
|
||||
data: Buffer.from(bytes).toString("base64"),
|
||||
mimeType: attachment.mimeType,
|
||||
} satisfies EffectAcpSchema.ContentBlock;
|
||||
}),
|
||||
detail: `Invalid attachment id '${attachment.id}'.`,
|
||||
});
|
||||
}
|
||||
const bytes = yield* fileSystem.readFile(attachmentPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: cause.message,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
type: "image",
|
||||
data: Buffer.from(bytes).toString("base64"),
|
||||
mimeType: attachment.mimeType,
|
||||
} satisfies EffectAcpSchema.ContentBlock;
|
||||
}),
|
||||
);
|
||||
const promptParts: Array<EffectAcpSchema.ContentBlock> = [
|
||||
...(text ? [{ type: "text" as const, text }] : []),
|
||||
...imagePromptParts,
|
||||
];
|
||||
|
||||
if (promptParts.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
}
|
||||
|
||||
ctx.currentModelId = currentModelId;
|
||||
const displayModel = currentModelId
|
||||
? resolveGrokAcpBaseModelId(currentModelId)
|
||||
: undefined;
|
||||
ctx.activeTurnId = turnId;
|
||||
if (steeringTurnId === undefined) {
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
}
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(displayModel ? { model: displayModel } : {}),
|
||||
};
|
||||
|
||||
if (steeringTurnId === undefined) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: displayModel ? { model: displayModel } : {},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
acp: ctx.acp,
|
||||
acpSessionId: ctx.acpSessionId,
|
||||
displayModel,
|
||||
promptParts,
|
||||
turnId,
|
||||
};
|
||||
}).pipe(
|
||||
Effect.tapCause(() =>
|
||||
Effect.sync(() => {
|
||||
ctx.promptsInFlight = Math.max(0, ctx.promptsInFlight - 1);
|
||||
}),
|
||||
),
|
||||
);
|
||||
const promptParts: Array<EffectAcpSchema.ContentBlock> = [
|
||||
...(text ? [{ type: "text" as const, text }] : []),
|
||||
...imagePromptParts,
|
||||
];
|
||||
|
||||
if (promptParts.length === 0) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "sendTurn",
|
||||
issue: "Turn requires non-empty text or attachments.",
|
||||
});
|
||||
}
|
||||
|
||||
ctx.currentModelId = currentModelId;
|
||||
const displayModel = currentModelId
|
||||
? resolveGrokAcpBaseModelId(currentModelId)
|
||||
: undefined;
|
||||
ctx.activeTurnId = turnId;
|
||||
ctx.lastPlanFingerprint = undefined;
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(displayModel ? { model: displayModel } : {}),
|
||||
};
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.started",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
payload: displayModel ? { model: displayModel } : {},
|
||||
});
|
||||
|
||||
return {
|
||||
acp: ctx.acp,
|
||||
acpSessionId: ctx.acpSessionId,
|
||||
displayModel,
|
||||
promptParts,
|
||||
turnId,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
const result = yield* prepared.acp
|
||||
.prompt({
|
||||
prompt: prepared.promptParts,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
),
|
||||
return yield* Effect.gen(function* () {
|
||||
const result = yield* prepared.acp
|
||||
.prompt({
|
||||
prompt: prepared.promptParts,
|
||||
})
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
mapAcpToAdapterError(PROVIDER, input.threadId, "session/prompt", error),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
if (ctx.acpSessionId !== prepared.acpSessionId) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: "Grok session changed before the turn completed.",
|
||||
});
|
||||
}
|
||||
|
||||
const existingTurnRecord = ctx.turns.find((turn) => turn.id === prepared.turnId);
|
||||
ctx.turns = existingTurnRecord
|
||||
? ctx.turns.map((turn) =>
|
||||
turn.id === prepared.turnId
|
||||
? {
|
||||
...turn,
|
||||
items: [...turn.items, { prompt: prepared.promptParts, result }],
|
||||
}
|
||||
: turn,
|
||||
)
|
||||
: [
|
||||
...ctx.turns,
|
||||
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
|
||||
];
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: prepared.turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
|
||||
};
|
||||
|
||||
// Only the last remaining prompt settles the turn — a steer-
|
||||
// superseded prompt resolving (usually cancelled) while another
|
||||
// is in flight or pending must leave the merged turn running.
|
||||
if (ctx.promptsInFlight === 1) {
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
return yield* withThreadLock(
|
||||
input.threadId,
|
||||
Effect.gen(function* () {
|
||||
const ctx = yield* requireSession(input.threadId);
|
||||
if (ctx.acpSessionId !== prepared.acpSessionId) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: PROVIDER,
|
||||
method: "session/prompt",
|
||||
detail: "Grok session changed before the turn completed.",
|
||||
});
|
||||
}
|
||||
|
||||
ctx.turns = [
|
||||
...ctx.turns,
|
||||
{ id: prepared.turnId, items: [{ prompt: prepared.promptParts, result }] },
|
||||
];
|
||||
ctx.session = {
|
||||
...ctx.session,
|
||||
activeTurnId: prepared.turnId,
|
||||
updatedAt: yield* nowIso,
|
||||
...(prepared.displayModel ? { model: prepared.displayModel } : {}),
|
||||
};
|
||||
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
...(yield* makeEventStamp()),
|
||||
provider: PROVIDER,
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
payload: {
|
||||
state: result.stopReason === "cancelled" ? "cancelled" : "completed",
|
||||
stopReason: result.stopReason ?? null,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId: prepared.turnId,
|
||||
resumeCursor: ctx.session.resumeCursor,
|
||||
};
|
||||
}),
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
const liveCtx = sessions.get(input.threadId);
|
||||
if (liveCtx) {
|
||||
liveCtx.promptsInFlight = Math.max(0, liveCtx.promptsInFlight - 1);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -395,6 +395,85 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("steers a running turn instead of opening a new one on mid-turn sendTurn", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-steer");
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "run 5 commands",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
});
|
||||
|
||||
// Steer: OpenCode queues the prompt into the busy session, so the
|
||||
// active turn id is reused instead of opening a new turn.
|
||||
const steeredTurn = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "actually run 15",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
});
|
||||
assert.equal(String(steeredTurn.turnId), String(turn.turnId));
|
||||
|
||||
const sessions = yield* adapter.listSessions();
|
||||
const session = sessions.find((entry) => entry.threadId === threadId);
|
||||
assert.equal(session?.status, "running");
|
||||
assert.equal(String(session?.activeTurnId), String(turn.turnId));
|
||||
assert.equal(runtimeMock.state.promptCalls.length, 2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps the running turn when a steer prompt fails", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-steer-failure");
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const turn = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "run 5 commands",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
});
|
||||
|
||||
runtimeMock.state.promptAsyncError = new Error("steer failed");
|
||||
const error = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "actually run 15",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("opencode"),
|
||||
model: "openai/gpt-5",
|
||||
},
|
||||
})
|
||||
.pipe(Effect.flip);
|
||||
|
||||
// The original turn keeps running — only the steer prompt failed.
|
||||
assert.equal(error._tag, "ProviderAdapterRequestError");
|
||||
const sessions = yield* adapter.listSessions();
|
||||
const session = sessions.find((entry) => entry.threadId === threadId);
|
||||
assert.equal(session?.status, "running");
|
||||
assert.equal(String(session?.activeTurnId), String(turn.turnId));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("passes agent and variant options for the adapter's bound custom instance id", () => {
|
||||
const instanceId = ProviderInstanceId.make("opencode_zen");
|
||||
const adapterLayer = Layer.effect(
|
||||
|
||||
@@ -1151,7 +1151,11 @@ export function makeOpenCodeAdapter(
|
||||
|
||||
const sendTurn: OpenCodeAdapterShape["sendTurn"] = Effect.fn("sendTurn")(function* (input) {
|
||||
const context = ensureSessionContext(sessions, input.threadId);
|
||||
const turnId = TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
|
||||
// A sendTurn while a turn is active is a steer: OpenCode queues the
|
||||
// prompt into the busy session and the work continues as one turn, so
|
||||
// the active turn id is reused instead of opening a new turn.
|
||||
const steeringTurnId = context.activeTurnId;
|
||||
const turnId = steeringTurnId ?? TurnId.make(`opencode-turn-${yield* randomUUIDv4}`);
|
||||
const modelSelection =
|
||||
input.modelSelection ??
|
||||
(context.session.model
|
||||
@@ -1206,14 +1210,16 @@ export function makeOpenCodeAdapter(
|
||||
{ clearLastError: true },
|
||||
);
|
||||
|
||||
yield* emit({
|
||||
...(yield* buildEventBase({ threadId: input.threadId, turnId })),
|
||||
type: "turn.started",
|
||||
payload: {
|
||||
model: modelSelection?.model ?? context.session.model,
|
||||
...(variant ? { effort: variant } : {}),
|
||||
},
|
||||
});
|
||||
if (steeringTurnId === undefined) {
|
||||
yield* emit({
|
||||
...(yield* buildEventBase({ threadId: input.threadId, turnId })),
|
||||
type: "turn.started",
|
||||
payload: {
|
||||
model: modelSelection?.model ?? context.session.model,
|
||||
...(variant ? { effort: variant } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
yield* runOpenCodeSdk("session.promptAsync", () =>
|
||||
context.client.session.promptAsync({
|
||||
@@ -1225,35 +1231,38 @@ export function makeOpenCodeAdapter(
|
||||
}),
|
||||
).pipe(
|
||||
Effect.mapError(toRequestError),
|
||||
// On failure: clear active-turn state, flip the session back to ready
|
||||
// with lastError set, emit turn.aborted, then let the typed error
|
||||
// propagate. We don't need to rebuild the error here — `toRequestError`
|
||||
// already produced the right shape.
|
||||
// On failure of a fresh turn: clear active-turn state, flip the
|
||||
// session back to ready with lastError set, emit turn.aborted, then
|
||||
// let the typed error propagate. We don't need to rebuild the error
|
||||
// here — `toRequestError` already produced the right shape. A failed
|
||||
// steer leaves the still-running original turn untouched.
|
||||
Effect.tapError((requestError) =>
|
||||
Effect.gen(function* () {
|
||||
context.activeTurnId = undefined;
|
||||
context.activeAgent = undefined;
|
||||
context.activeVariant = undefined;
|
||||
yield* updateProviderSession(
|
||||
context,
|
||||
{
|
||||
status: "ready",
|
||||
model: modelSelection?.model ?? context.session.model,
|
||||
lastError: requestError.detail,
|
||||
},
|
||||
{ clearActiveTurnId: true },
|
||||
);
|
||||
yield* emit({
|
||||
...(yield* buildEventBase({
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
})),
|
||||
type: "turn.aborted",
|
||||
payload: {
|
||||
reason: requestError.detail,
|
||||
},
|
||||
});
|
||||
}),
|
||||
steeringTurnId !== undefined
|
||||
? Effect.void
|
||||
: Effect.gen(function* () {
|
||||
context.activeTurnId = undefined;
|
||||
context.activeAgent = undefined;
|
||||
context.activeVariant = undefined;
|
||||
yield* updateProviderSession(
|
||||
context,
|
||||
{
|
||||
status: "ready",
|
||||
model: modelSelection?.model ?? context.session.model,
|
||||
lastError: requestError.detail,
|
||||
},
|
||||
{ clearActiveTurnId: true },
|
||||
);
|
||||
yield* emit({
|
||||
...(yield* buildEventBase({
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
})),
|
||||
type: "turn.aborted",
|
||||
payload: {
|
||||
reason: requestError.detail,
|
||||
},
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -594,6 +594,77 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
]);
|
||||
});
|
||||
|
||||
it.effect("does not run provider probes during layer construction", () =>
|
||||
Effect.gen(function* () {
|
||||
const codexDriver = ProviderDriverKind.make("codex");
|
||||
const codexInstanceId = ProviderInstanceId.make("codex");
|
||||
const initialProvider = {
|
||||
instanceId: codexInstanceId,
|
||||
driver: codexDriver,
|
||||
status: "warning",
|
||||
enabled: true,
|
||||
installed: false,
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-06-10T00:00:00.000Z",
|
||||
version: null,
|
||||
message: "Checking Codex provider status.",
|
||||
models: [],
|
||||
slashCommands: [],
|
||||
skills: [],
|
||||
} as const satisfies ServerProvider;
|
||||
const refreshCalls = yield* Ref.make(0);
|
||||
const instance = {
|
||||
instanceId: codexInstanceId,
|
||||
driverKind: codexDriver,
|
||||
continuationIdentity: {
|
||||
driverKind: codexDriver,
|
||||
continuationKey: "codex:instance:codex",
|
||||
},
|
||||
displayName: undefined,
|
||||
enabled: true,
|
||||
snapshot: {
|
||||
maintenanceCapabilities: makeManualOnlyProviderMaintenanceCapabilities({
|
||||
provider: codexDriver,
|
||||
packageName: null,
|
||||
}),
|
||||
getSnapshot: Effect.succeed(initialProvider),
|
||||
refresh: Ref.update(refreshCalls, (count) => count + 1).pipe(
|
||||
Effect.andThen(Effect.never),
|
||||
),
|
||||
streamChanges: Stream.empty,
|
||||
},
|
||||
adapter: {} as ProviderInstance["adapter"],
|
||||
textGeneration: {} as ProviderInstance["textGeneration"],
|
||||
} satisfies ProviderInstance;
|
||||
const instanceRegistryLayer = Layer.succeed(ProviderInstanceRegistry, {
|
||||
getInstance: (instanceId) =>
|
||||
Effect.succeed(instanceId === codexInstanceId ? instance : undefined),
|
||||
listInstances: Effect.succeed([instance]),
|
||||
listUnavailable: Effect.succeed([]),
|
||||
streamChanges: Stream.empty,
|
||||
subscribeChanges: Effect.flatMap(PubSub.unbounded<void>(), PubSub.subscribe),
|
||||
});
|
||||
const scope = yield* Scope.make();
|
||||
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
|
||||
const runtimeServices = yield* Layer.build(
|
||||
ProviderRegistryLive.pipe(
|
||||
Layer.provideMerge(instanceRegistryLayer),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-provider-registry-background-refresh-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
).pipe(Scope.provide(scope));
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
assert.deepStrictEqual(yield* registry.getProviders, [initialProvider]);
|
||||
assert.strictEqual(yield* Ref.get(refreshCalls), 0);
|
||||
}).pipe(Effect.provide(runtimeServices));
|
||||
}),
|
||||
);
|
||||
|
||||
it("persists merged provider snapshots for the providers that were refreshed", () => {
|
||||
const previousProviders = [
|
||||
{
|
||||
@@ -1042,7 +1113,17 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const registry = yield* ProviderRegistry;
|
||||
const providers = yield* registry.getProviders;
|
||||
let providers = yield* registry.getProviders;
|
||||
for (
|
||||
let attempts = 0;
|
||||
attempts < 50 &&
|
||||
providers.find((provider) => provider.instanceId === "codex_personal")?.status !==
|
||||
"error";
|
||||
attempts += 1
|
||||
) {
|
||||
yield* Effect.yieldNow;
|
||||
providers = yield* registry.getProviders;
|
||||
}
|
||||
const codexPersonal = providers.find(
|
||||
(provider) => provider.instanceId === "codex_personal",
|
||||
);
|
||||
@@ -1072,9 +1153,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
// instance and rebuild it so a fresh probe runs with the new binary.
|
||||
// This test drives the real settings stream → registry reconcile →
|
||||
// aggregator sync pipeline and asserts that `getProviders` reflects
|
||||
// the new probe's outcome. If `syncLiveSources` stops awaiting the
|
||||
// rebuilt instance's refresh (previous bug mode), the aggregator
|
||||
// keeps the old snapshot and this test fails.
|
||||
// the new background probe's outcome.
|
||||
//
|
||||
it.effect("re-probes when settings change the codex binaryPath", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -1124,7 +1203,18 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
// the two probe runs is `checkedAt` — each probe stamps a
|
||||
// fresh DateTime, so we capture it and assert it advances
|
||||
// after the settings mutation.
|
||||
const initialProviders = yield* registry.getProviders;
|
||||
let initialProviders = yield* registry.getProviders;
|
||||
for (
|
||||
let attempts = 0;
|
||||
attempts < 50 &&
|
||||
initialProviders.find((provider) => provider.instanceId === "codex")?.status !==
|
||||
"error";
|
||||
attempts += 1
|
||||
) {
|
||||
yield* TestClock.adjust("10 millis");
|
||||
yield* Effect.yieldNow;
|
||||
initialProviders = yield* registry.getProviders;
|
||||
}
|
||||
const initialCodex = initialProviders.find(
|
||||
(provider) => provider.instanceId === "codex",
|
||||
);
|
||||
@@ -1144,8 +1234,8 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
// envelope changed because `binaryPath` differs → `entryEqual`
|
||||
// is false). The registry's `Stream.runForEach(
|
||||
// instanceRegistry.streamChanges, () => syncLiveSources)`
|
||||
// fires `syncLiveSources`, which subscribes + awaits a fresh
|
||||
// refresh on the rebuilt instance.
|
||||
// fires `syncLiveSources`, which subscribes and launches a fresh
|
||||
// background refresh on the rebuilt instance.
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: { enabled: true, binaryPath: secondMissing },
|
||||
@@ -1158,7 +1248,11 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
|
||||
for (let attempts = 0; attempts < 60; attempts += 1) {
|
||||
const providers = yield* registry.getProviders;
|
||||
const codex = providers.find((provider) => provider.instanceId === "codex");
|
||||
if (codex !== undefined && codex.checkedAt !== initialCheckedAt) {
|
||||
if (
|
||||
codex !== undefined &&
|
||||
codex.status === "error" &&
|
||||
codex.checkedAt !== initialCheckedAt
|
||||
) {
|
||||
return providers;
|
||||
}
|
||||
yield* TestClock.adjust("50 millis");
|
||||
|
||||
@@ -492,16 +492,15 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
* - subscribe to each newly-added or rebuilt instance's
|
||||
* `streamChanges` (so periodic + enrichment refreshes land in
|
||||
* `providersRef`);
|
||||
* - force-refresh each newly-added/rebuilt instance and feed the
|
||||
* result directly into `providersRef`, bypassing the PubSub
|
||||
* attachment race that otherwise drops the initial probe;
|
||||
* - read each newly-added/rebuilt instance's current snapshot after
|
||||
* subscribing, closing the race with its independently-running
|
||||
* background startup probe;
|
||||
* - prune `providersRef` of instances that no longer exist.
|
||||
*
|
||||
* Initial refreshes are awaited in parallel rather than forked, so
|
||||
* callers (layer build; `streamChanges` watcher) see fully-probed
|
||||
* state on return. This matters for layer build in particular:
|
||||
* consumers reading `getProviders` immediately after layer build
|
||||
* expect the probe to have already landed.
|
||||
* Provider refreshes are owned by each managed provider and never run
|
||||
* on this layer's construction path. Consumers see cached or pending
|
||||
* snapshots immediately, then receive live probe results through the
|
||||
* already-attached change stream.
|
||||
*
|
||||
* Per-instance subscription fibers are not tracked explicitly. When
|
||||
* a rebuilt instance's old child scope closes, its PubSub shuts
|
||||
@@ -543,27 +542,31 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
}
|
||||
|
||||
// Fork long-lived subscriptions to each new/rebuilt instance's
|
||||
// change stream BEFORE kicking off refreshes — if the driver's
|
||||
// own initial probe (line 140 in `makeManagedServerProvider`)
|
||||
// wins the refreshSemaphore race, its PubSub publish must land
|
||||
// in an active subscriber or the result is dropped.
|
||||
// change stream before reading its current snapshot. If the
|
||||
// driver's own initial probe finishes during this sync, either
|
||||
// the current read or the active subscriber observes the result.
|
||||
for (const [, instance] of newlyAdded) {
|
||||
const source = buildSnapshotSource(instance);
|
||||
yield* Stream.runForEach(source.streamChanges, (provider) =>
|
||||
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
|
||||
).pipe(Effect.forkScoped);
|
||||
}
|
||||
yield* Effect.yieldNow;
|
||||
|
||||
// Force-refresh every new/rebuilt instance in parallel and wait
|
||||
// for them all to complete. The refresh's result is piped
|
||||
// directly into `syncProvider`, so `providersRef` is populated
|
||||
// deterministically by the time this block returns — regardless
|
||||
// of PubSub subscription timing. Failures are logged and
|
||||
// swallowed so one bad driver can't wedge the whole registry.
|
||||
// Snapshot current state without starting a probe. Managed providers
|
||||
// launch their startup refresh independently, so this closes the
|
||||
// subscription race without putting external work on the registry
|
||||
// or HTTP server construction path.
|
||||
yield* Effect.forEach(
|
||||
newlyAdded,
|
||||
([, instance]) =>
|
||||
refreshOneSource(buildSnapshotSource(instance)).pipe(Effect.ignoreCause({ log: true })),
|
||||
Effect.gen(function* () {
|
||||
const source = buildSnapshotSource(instance);
|
||||
const provider = yield* source.getSnapshot;
|
||||
yield* correlateSnapshotWithSource(source, provider).pipe(
|
||||
Effect.flatMap(syncProvider),
|
||||
);
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
{ concurrency: "unbounded", discard: true },
|
||||
);
|
||||
yield* upsertProviders(unavailableProviders, {
|
||||
@@ -654,9 +657,9 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
// was dropped, which made any settings change that replaced an
|
||||
// instance never propagate to the aggregator's `providersRef`.)
|
||||
const instanceChanges = yield* instanceRegistry.subscribeChanges;
|
||||
// Initial sync: subscribe + kick off refreshes for every instance
|
||||
// present at boot. Run synchronously so consumers pulling immediately
|
||||
// after the layer build see the correct aggregator state.
|
||||
// Initial sync attaches subscriptions and snapshots current state for
|
||||
// every instance present at boot. Provider probes are already running in
|
||||
// their managed background fibers and never block this layer.
|
||||
yield* syncLiveSources;
|
||||
// React to registry mutations — instance added / removed / rebuilt.
|
||||
// `Stream.fromSubscription` builds a stream over the pre-acquired
|
||||
|
||||
@@ -129,6 +129,7 @@ describe("makeManagedServerProvider", () => {
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* Effect.yieldNow;
|
||||
assert.strictEqual(yield* Ref.get(checkCalls), 1);
|
||||
|
||||
yield* Deferred.succeed(releaseCheck, undefined);
|
||||
|
||||
|
||||
@@ -152,11 +152,7 @@ export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(
|
||||
|
||||
return {
|
||||
maintenanceCapabilities: input.maintenanceCapabilities,
|
||||
getSnapshot: input.getSettings.pipe(
|
||||
Effect.flatMap(applySnapshot),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orDie,
|
||||
),
|
||||
getSnapshot: Ref.get(snapshotStateRef).pipe(Effect.map((state) => state.snapshot)),
|
||||
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
|
||||
@@ -87,6 +87,12 @@ import * as NetService from "@t3tools/shared/Net";
|
||||
import * as RelayClient from "@t3tools/shared/relayClient";
|
||||
import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
|
||||
|
||||
// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
|
||||
// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
|
||||
// already closes the websocket gracefully. Do not add an artificial drain before
|
||||
// those finalizers get a chance to run.
|
||||
const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
|
||||
|
||||
const PtyAdapterLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
if (typeof Bun !== "undefined") {
|
||||
@@ -116,6 +122,7 @@ const HttpServerLive = Layer.unwrap(
|
||||
return BunHttpServer.layer({
|
||||
port: config.port,
|
||||
...(config.host ? { hostname: config.host } : {}),
|
||||
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
|
||||
});
|
||||
} else {
|
||||
const [NodeHttpServer, NodeHttp] = yield* Effect.all([
|
||||
@@ -125,6 +132,7 @@ const HttpServerLive = Layer.unwrap(
|
||||
return NodeHttpServer.layer(NodeHttp.createServer, {
|
||||
host: config.host,
|
||||
port: config.port,
|
||||
gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -32,7 +32,7 @@ function makeFakeCodexBinary(
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
requireImage?: boolean;
|
||||
requireFastServiceTier?: boolean;
|
||||
requireServiceTier?: string;
|
||||
requireReasoningEffort?: string;
|
||||
forbidReasoningEffort?: boolean;
|
||||
stdinMustContain?: string;
|
||||
@@ -52,7 +52,7 @@ function makeFakeCodexBinary(
|
||||
"#!/bin/sh",
|
||||
'output_path=""',
|
||||
'seen_image="0"',
|
||||
'seen_fast_service_tier="0"',
|
||||
'seen_service_tier=""',
|
||||
'seen_reasoning_effort=""',
|
||||
"while [ $# -gt 0 ]; do",
|
||||
' if [ "$1" = "--image" ]; then',
|
||||
@@ -65,9 +65,11 @@ function makeFakeCodexBinary(
|
||||
" fi",
|
||||
' if [ "$1" = "--config" ]; then',
|
||||
" shift",
|
||||
' if [ "$1" = "service_tier=\\"fast\\"" ]; then',
|
||||
' seen_fast_service_tier="1"',
|
||||
" fi",
|
||||
' case "$1" in',
|
||||
" service_tier=*)",
|
||||
' seen_service_tier="$1"',
|
||||
" ;;",
|
||||
" esac",
|
||||
' case "$1" in',
|
||||
" model_reasoning_effort=*)",
|
||||
' seen_reasoning_effort="$1"',
|
||||
@@ -93,10 +95,10 @@ function makeFakeCodexBinary(
|
||||
"fi",
|
||||
]
|
||||
: []),
|
||||
...(input.requireFastServiceTier
|
||||
...(input.requireServiceTier
|
||||
? [
|
||||
'if [ "$seen_fast_service_tier" != "1" ]; then',
|
||||
' printf "%s\\n" "missing fast service tier config" >&2',
|
||||
`if [ "$seen_service_tier" != "service_tier=\\"${input.requireServiceTier}\\"" ]; then`,
|
||||
' printf "%s\\n" "unexpected service tier config: $seen_service_tier" >&2',
|
||||
` exit 5`,
|
||||
"fi",
|
||||
]
|
||||
@@ -161,7 +163,7 @@ function withFakeCodexEnv<A, E, R>(
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
requireImage?: boolean;
|
||||
requireFastServiceTier?: boolean;
|
||||
requireServiceTier?: string;
|
||||
requireReasoningEffort?: string;
|
||||
forbidReasoningEffort?: boolean;
|
||||
stdinMustContain?: string;
|
||||
@@ -209,7 +211,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"forwards codex fast mode and non-default reasoning effort into codex exec config",
|
||||
"forwards codex service tier and non-default reasoning effort into codex exec config",
|
||||
() =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
@@ -217,7 +219,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
subject: "Add important change",
|
||||
body: "",
|
||||
}),
|
||||
requireFastServiceTier: true,
|
||||
requireServiceTier: "priority",
|
||||
requireReasoningEffort: "xhigh",
|
||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
@@ -229,7 +231,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
|
||||
{ id: "reasoningEffort", value: "xhigh" },
|
||||
{ id: "fastMode", value: true },
|
||||
{ id: "serviceTier", value: "priority" },
|
||||
]),
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -32,10 +32,8 @@ import {
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
import {
|
||||
getModelSelectionBooleanOptionValue,
|
||||
getModelSelectionStringOptionValue,
|
||||
} from "@t3tools/shared/model";
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
import { getCodexServiceTierOptionValue } from "../codexModelOptions.ts";
|
||||
|
||||
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
@@ -181,6 +179,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
const reasoningEffort =
|
||||
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
|
||||
CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
const serviceTier = getCodexServiceTierOptionValue(modelSelection);
|
||||
const command = ChildProcess.make(
|
||||
codexConfig.binaryPath || "codex",
|
||||
[
|
||||
@@ -193,9 +192,7 @@ export const makeCodexTextGeneration = Effect.fn("makeCodexTextGeneration")(func
|
||||
modelSelection.model,
|
||||
"--config",
|
||||
`model_reasoning_effort="${reasoningEffort}"`,
|
||||
...(getModelSelectionBooleanOptionValue(modelSelection, "fastMode") === true
|
||||
? ["--config", `service_tier="fast"`]
|
||||
: []),
|
||||
...(serviceTier ? ["--config", `service_tier="${serviceTier}"`] : []),
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
|
||||
@@ -68,6 +68,17 @@ export interface GitStatusDetails {
|
||||
aheadOfDefaultCount: number;
|
||||
}
|
||||
|
||||
export interface GitRemoteStatusDetails {
|
||||
isRepo: boolean;
|
||||
isDefaultBranch: boolean;
|
||||
branch: string | null;
|
||||
upstreamRef: string | null;
|
||||
hasUpstream: boolean;
|
||||
aheadCount: number;
|
||||
behindCount: number;
|
||||
aheadOfDefaultCount: number;
|
||||
}
|
||||
|
||||
export interface GitPreparedCommitContext {
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
@@ -162,6 +173,9 @@ export interface GitVcsDriverShape {
|
||||
readonly status: (input: VcsStatusInput) => Effect.Effect<VcsStatusResult, GitCommandError>;
|
||||
readonly statusDetails: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
readonly statusDetailsLocal: (cwd: string) => Effect.Effect<GitStatusDetails, GitCommandError>;
|
||||
readonly statusDetailsRemote: (
|
||||
cwd: string,
|
||||
) => Effect.Effect<GitRemoteStatusDetails, GitCommandError>;
|
||||
readonly prepareCommitContext: (
|
||||
cwd: string,
|
||||
filePaths?: readonly string[],
|
||||
|
||||
@@ -155,6 +155,67 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reports remote divergence without reading working-tree details", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
|
||||
const { initialBranch } = yield* initRepoWithCommit(cwd);
|
||||
yield* git(remote, ["init", "--bare"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", remote]);
|
||||
yield* git(cwd, ["push", "-u", "origin", initialBranch]);
|
||||
yield* git(cwd, ["checkout", "-b", "feature/remote-status"]);
|
||||
yield* writeTextFile(cwd, "feature.txt", "feature\n");
|
||||
yield* git(cwd, ["add", "feature.txt"]);
|
||||
yield* git(cwd, ["commit", "-m", "feature commit"]);
|
||||
yield* git(cwd, ["push", "-u", "origin", "feature/remote-status"]);
|
||||
yield* writeTextFile(cwd, "untracked.txt", "local-only\n");
|
||||
|
||||
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd);
|
||||
|
||||
assert.equal(status.isRepo, true);
|
||||
assert.equal(status.branch, "feature/remote-status");
|
||||
assert.equal(status.hasUpstream, true);
|
||||
assert.equal(status.aheadCount, 0);
|
||||
assert.equal(status.behindCount, 0);
|
||||
assert.equal(status.aheadOfDefaultCount, 1);
|
||||
assert.notProperty(status, "workingTree");
|
||||
assert.notProperty(status, "hasWorkingTreeChanges");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses origin HEAD for default-branch detection with a non-origin upstream", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
const origin = yield* makeTmpDir("git-vcs-driver-origin-");
|
||||
const upstream = yield* makeTmpDir("git-vcs-driver-upstream-");
|
||||
yield* initRepoWithCommit(cwd);
|
||||
yield* git(origin, ["init", "--bare"]);
|
||||
yield* git(upstream, ["init", "--bare"]);
|
||||
yield* git(cwd, ["branch", "-M", "main"]);
|
||||
yield* git(cwd, ["remote", "add", "origin", origin]);
|
||||
yield* git(cwd, ["remote", "add", "upstream", upstream]);
|
||||
yield* git(cwd, ["push", "origin", "main"]);
|
||||
yield* git(cwd, ["push", "upstream", "main"]);
|
||||
yield* git(cwd, ["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main"]);
|
||||
yield* git(cwd, ["checkout", "-b", "release"]);
|
||||
yield* writeTextFile(cwd, "release.txt", "release\n");
|
||||
yield* git(cwd, ["add", "release.txt"]);
|
||||
yield* git(cwd, ["commit", "-m", "release commit"]);
|
||||
yield* git(cwd, ["push", "-u", "upstream", "release"]);
|
||||
yield* git(cwd, [
|
||||
"symbolic-ref",
|
||||
"refs/remotes/upstream/HEAD",
|
||||
"refs/remotes/upstream/release",
|
||||
]);
|
||||
|
||||
const status = yield* (yield* GitVcsDriver.GitVcsDriver).statusDetailsRemote(cwd);
|
||||
|
||||
assert.equal(status.branch, "release");
|
||||
assert.equal(status.upstreamRef, "upstream/release");
|
||||
assert.equal(status.isDefaultBranch, false);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("disables SSH askpass for background upstream status fetches", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTmpDir();
|
||||
|
||||
@@ -71,6 +71,16 @@ const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitStatusDetail
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
});
|
||||
const NON_REPOSITORY_REMOTE_STATUS_DETAILS = Object.freeze<GitVcsDriver.GitRemoteStatusDetails>({
|
||||
isRepo: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
});
|
||||
|
||||
type TraceTailState = {
|
||||
processedChars: number;
|
||||
@@ -1154,6 +1164,78 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
return Number.isFinite(parsed) ? Math.max(0, parsed) : 0;
|
||||
});
|
||||
|
||||
const readStatusDetailsRemote = Effect.fn("readStatusDetailsRemote")(function* (cwd: string) {
|
||||
const branchResult = yield* executeGit(
|
||||
"GitVcsDriver.statusDetailsRemote.branch",
|
||||
cwd,
|
||||
["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
{ allowNonZeroExit: true },
|
||||
).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
|
||||
|
||||
if (branchResult === null) {
|
||||
return NON_REPOSITORY_REMOTE_STATUS_DETAILS;
|
||||
}
|
||||
if (branchResult.exitCode !== 0) {
|
||||
const stderr = branchResult.stderr.trim();
|
||||
return yield* createGitCommandError(
|
||||
"GitVcsDriver.statusDetailsRemote.branch",
|
||||
cwd,
|
||||
["rev-parse", "--abbrev-ref", "HEAD"],
|
||||
stderr || "git branch lookup failed",
|
||||
);
|
||||
}
|
||||
|
||||
const branchValue = branchResult.stdout.trim();
|
||||
const branch = branchValue.length > 0 && branchValue !== "HEAD" ? branchValue : null;
|
||||
const upstream = yield* resolveCurrentUpstream(cwd);
|
||||
const upstreamRef = upstream?.upstreamRef ?? null;
|
||||
let aheadCount = 0;
|
||||
let behindCount = 0;
|
||||
|
||||
if (upstreamRef) {
|
||||
const divergence = yield* executeGit(
|
||||
"GitVcsDriver.statusDetailsRemote.divergence",
|
||||
cwd,
|
||||
["rev-list", "--left-right", "--count", `HEAD...${upstreamRef}`],
|
||||
{ allowNonZeroExit: true },
|
||||
);
|
||||
if (divergence.exitCode === 0) {
|
||||
const [aheadRaw, behindRaw] = divergence.stdout.trim().split(/\s+/);
|
||||
const parsedAhead = Number.parseInt(aheadRaw ?? "0", 10);
|
||||
const parsedBehind = Number.parseInt(behindRaw ?? "0", 10);
|
||||
aheadCount = Number.isFinite(parsedAhead) ? Math.max(0, parsedAhead) : 0;
|
||||
behindCount = Number.isFinite(parsedBehind) ? Math.max(0, parsedBehind) : 0;
|
||||
}
|
||||
} else if (branch) {
|
||||
aheadCount = yield* computeAheadCountAgainstBase(cwd, branch).pipe(
|
||||
Effect.orElseSucceed(() => 0),
|
||||
);
|
||||
}
|
||||
|
||||
const defaultBranch = yield* resolveDefaultBranchName(cwd, "origin");
|
||||
const isDefaultBranch =
|
||||
branch !== null &&
|
||||
(branch === defaultBranch ||
|
||||
(defaultBranch === null && (branch === "main" || branch === "master")));
|
||||
const aheadOfDefaultCount =
|
||||
branch && !isDefaultBranch
|
||||
? upstreamRef === null
|
||||
? aheadCount
|
||||
: yield* computeAheadCountAgainstBase(cwd, branch).pipe(Effect.orElseSucceed(() => 0))
|
||||
: 0;
|
||||
|
||||
return {
|
||||
isRepo: true,
|
||||
isDefaultBranch,
|
||||
branch,
|
||||
upstreamRef,
|
||||
hasUpstream: upstreamRef !== null,
|
||||
aheadCount,
|
||||
behindCount,
|
||||
aheadOfDefaultCount,
|
||||
};
|
||||
});
|
||||
|
||||
const readBranchRecency = Effect.fn("readBranchRecency")(function* (cwd: string) {
|
||||
const branchRecency = yield* executeGit(
|
||||
"GitVcsDriver.readBranchRecency",
|
||||
@@ -1356,6 +1438,16 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
},
|
||||
);
|
||||
|
||||
const statusDetailsRemote: GitVcsDriver.GitVcsDriverShape["statusDetailsRemote"] = Effect.fn(
|
||||
"statusDetailsRemote",
|
||||
)(function* (cwd) {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
return yield* readStatusDetailsRemote(cwd);
|
||||
});
|
||||
|
||||
const status: GitVcsDriver.GitVcsDriverShape["status"] = (input) =>
|
||||
statusDetails(input.cwd).pipe(
|
||||
Effect.map((details) => ({
|
||||
@@ -1402,7 +1494,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
const stagedPatch = yield* runGitStdoutWithOptions(
|
||||
"GitVcsDriver.prepareCommitContext.stagedPatch",
|
||||
cwd,
|
||||
["diff", "--cached", "--patch", "--minimal"],
|
||||
["diff", "--no-ext-diff", "--cached", "--patch", "--minimal"],
|
||||
{
|
||||
maxOutputBytes: PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES,
|
||||
appendTruncationMarker: true,
|
||||
@@ -1639,7 +1731,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
runGitStdoutWithOptions(
|
||||
"GitVcsDriver.readRangeContext.diffPatch",
|
||||
cwd,
|
||||
["diff", "--patch", "--minimal", range],
|
||||
["diff", "--no-ext-diff", "--patch", "--minimal", range],
|
||||
{
|
||||
maxOutputBytes: RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES,
|
||||
appendTruncationMarker: true,
|
||||
@@ -2302,6 +2394,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
|
||||
status,
|
||||
statusDetails,
|
||||
statusDetailsLocal,
|
||||
statusDetailsRemote,
|
||||
prepareCommitContext,
|
||||
commit,
|
||||
pushCurrentBranch,
|
||||
|
||||
@@ -10,6 +10,7 @@ import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as TestClock from "effect/testing/TestClock";
|
||||
import type {
|
||||
VcsStatusLocalResult,
|
||||
VcsStatusRemoteResult,
|
||||
@@ -310,6 +311,48 @@ describe("VcsStatusBroadcaster", () => {
|
||||
}).pipe(Effect.provide(makeTestLayer(state)));
|
||||
});
|
||||
|
||||
it.effect("delays automatic refresh when a cached remote snapshot is available", () => {
|
||||
const state = {
|
||||
currentLocalStatus: baseLocalStatus,
|
||||
currentRemoteStatus: baseRemoteStatus,
|
||||
localStatusCalls: 0,
|
||||
remoteStatusCalls: 0,
|
||||
localInvalidationCalls: 0,
|
||||
remoteInvalidationCalls: 0,
|
||||
};
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster;
|
||||
yield* broadcaster.getStatus({ cwd: "/repo" });
|
||||
const scope = yield* Scope.make();
|
||||
const snapshotDeferred = yield* Deferred.make<VcsStatusStreamEvent>();
|
||||
yield* Stream.runForEach(
|
||||
broadcaster.streamStatus(
|
||||
{ cwd: "/repo" },
|
||||
{ automaticRemoteRefreshInterval: Effect.succeed(Duration.minutes(1)) },
|
||||
),
|
||||
(event) =>
|
||||
event._tag === "snapshot"
|
||||
? Deferred.succeed(snapshotDeferred, event).pipe(Effect.ignore)
|
||||
: Effect.void,
|
||||
).pipe(Effect.forkIn(scope));
|
||||
|
||||
yield* Deferred.await(snapshotDeferred);
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
assert.equal(state.remoteInvalidationCalls, 0);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(59));
|
||||
assert.equal(state.remoteStatusCalls, 1);
|
||||
|
||||
yield* TestClock.adjust(Duration.seconds(1));
|
||||
yield* Effect.yieldNow;
|
||||
assert.equal(state.remoteStatusCalls, 2);
|
||||
assert.equal(state.remoteInvalidationCalls, 1);
|
||||
|
||||
yield* Scope.close(scope, Exit.void);
|
||||
}).pipe(Effect.provide(Layer.merge(makeTestLayer(state), TestClock.layer())));
|
||||
});
|
||||
|
||||
it("backs off remote refresh failures exponentially and honors larger configured intervals", () => {
|
||||
assert.equal(
|
||||
Duration.toMillis(VcsStatusBroadcaster.remoteRefreshFailureDelay(1, Duration.seconds(1))),
|
||||
|
||||
@@ -257,6 +257,7 @@ export const layer = Layer.effect(
|
||||
const makeRemoteRefreshLoop = (
|
||||
cwd: string,
|
||||
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
|
||||
refreshImmediately: boolean,
|
||||
) => {
|
||||
return Effect.gen(function* () {
|
||||
const consecutiveFailuresRef = yield* Ref.make(0);
|
||||
@@ -289,6 +290,15 @@ export const layer = Layer.effect(
|
||||
return nextDelay;
|
||||
});
|
||||
|
||||
if (!refreshImmediately) {
|
||||
const configuredInterval = yield* automaticRemoteRefreshInterval;
|
||||
yield* Effect.sleep(
|
||||
Duration.isZero(configuredInterval)
|
||||
? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
|
||||
: configuredInterval,
|
||||
);
|
||||
}
|
||||
|
||||
return yield* refreshRemoteStatusIfEnabled.pipe(
|
||||
Effect.repeat(
|
||||
Schedule.identity<Duration.Duration>().pipe(
|
||||
@@ -303,6 +313,7 @@ export const layer = Layer.effect(
|
||||
const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
|
||||
cwd: string,
|
||||
automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
|
||||
refreshImmediately: boolean,
|
||||
) {
|
||||
yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
|
||||
const existing = activePollers.get(cwd);
|
||||
@@ -315,7 +326,7 @@ export const layer = Layer.effect(
|
||||
return Effect.succeed([undefined, nextPollers] as const);
|
||||
}
|
||||
|
||||
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval).pipe(
|
||||
return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval, refreshImmediately).pipe(
|
||||
Effect.forkIn(broadcasterScope),
|
||||
Effect.map((fiber) => {
|
||||
const nextPollers = new Map(activePollers);
|
||||
@@ -363,11 +374,13 @@ export const layer = Layer.effect(
|
||||
const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
|
||||
const subscription = yield* PubSub.subscribe(changesPubSub);
|
||||
const initialLocal = yield* getOrLoadLocalStatus(cwd);
|
||||
const initialRemote = (yield* getCachedStatus(cwd))?.remote?.value ?? null;
|
||||
const cachedStatus = yield* getCachedStatus(cwd);
|
||||
const initialRemote = cachedStatus?.remote?.value ?? null;
|
||||
yield* retainRemotePoller(
|
||||
cwd,
|
||||
options?.automaticRemoteRefreshInterval ??
|
||||
Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
|
||||
cachedStatus?.remote === null || cachedStatus?.remote === undefined,
|
||||
);
|
||||
|
||||
const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
|
||||
|
||||
@@ -665,6 +665,7 @@ function UncachedShikiCodeBlock({
|
||||
interface MarkdownFileLinkProps {
|
||||
href: string;
|
||||
targetPath: string;
|
||||
iconPath: string;
|
||||
displayPath: string;
|
||||
label: string;
|
||||
copyMarkdown: string;
|
||||
@@ -938,6 +939,7 @@ function MarkdownExternalLinkContent({
|
||||
const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
href,
|
||||
targetPath,
|
||||
iconPath,
|
||||
displayPath,
|
||||
label,
|
||||
copyMarkdown,
|
||||
@@ -1044,7 +1046,7 @@ const MarkdownFileLink = memo(function MarkdownFileLink({
|
||||
}}
|
||||
onContextMenu={handleContextMenu}
|
||||
>
|
||||
<FileTagChipContent path={targetPath} label={label} theme={theme} selectable />
|
||||
<FileTagChipContent path={iconPath} label={label} theme={theme} selectable />
|
||||
</a>
|
||||
}
|
||||
/>
|
||||
@@ -1067,6 +1069,7 @@ function areMarkdownFileLinkPropsEqual(
|
||||
return (
|
||||
previous.href === next.href &&
|
||||
previous.targetPath === next.targetPath &&
|
||||
previous.iconPath === next.iconPath &&
|
||||
previous.displayPath === next.displayPath &&
|
||||
previous.label === next.label &&
|
||||
previous.copyMarkdown === next.copyMarkdown &&
|
||||
@@ -1186,6 +1189,7 @@ function ChatMarkdown({
|
||||
<MarkdownFileLink
|
||||
href={fileLinkMeta.targetPath}
|
||||
targetPath={fileLinkMeta.targetPath}
|
||||
iconPath={fileLinkMeta.filePath}
|
||||
displayPath={fileLinkMeta.displayPath}
|
||||
label={labelParts.join(" · ")}
|
||||
copyMarkdown={`[${fileLinkMeta.basename}](${normalizedHref})`}
|
||||
|
||||
@@ -50,7 +50,6 @@ import {
|
||||
parseStandaloneComposerSlashCommand,
|
||||
} from "../composer-logic";
|
||||
import {
|
||||
deriveCompletionDividerBeforeEntryId,
|
||||
derivePendingApprovals,
|
||||
derivePendingUserInputs,
|
||||
derivePhase,
|
||||
@@ -61,9 +60,7 @@ import {
|
||||
findLatestProposedPlan,
|
||||
deriveWorkLogEntries,
|
||||
hasActionableProposedPlan,
|
||||
hasToolActivityForTurn,
|
||||
isLatestTurnSettled,
|
||||
formatElapsed,
|
||||
} from "../session-logic";
|
||||
import { type LegendListRef } from "@legendapp/list/react";
|
||||
import {
|
||||
@@ -1517,14 +1514,7 @@ export default function ChatView(props: ChatViewProps) {
|
||||
const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
|
||||
const workLogEntries = useMemo(
|
||||
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
|
||||
[activeLatestTurn?.turnId, threadActivities],
|
||||
);
|
||||
const latestTurnHasToolActivity = useMemo(
|
||||
() => hasToolActivityForTurn(threadActivities, activeLatestTurn?.turnId),
|
||||
[activeLatestTurn?.turnId, threadActivities],
|
||||
);
|
||||
const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);
|
||||
const pendingApprovals = useMemo(
|
||||
() => derivePendingApprovals(threadActivities),
|
||||
[threadActivities],
|
||||
@@ -1859,25 +1849,6 @@ export default function ChatView(props: ChatViewProps) {
|
||||
return byUserMessageId;
|
||||
}, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);
|
||||
|
||||
const completionSummary = useMemo(() => {
|
||||
if (!latestTurnSettled) return null;
|
||||
if (!activeLatestTurn?.startedAt) return null;
|
||||
if (!activeLatestTurn.completedAt) return null;
|
||||
if (!latestTurnHasToolActivity) return null;
|
||||
|
||||
const elapsed = formatElapsed(activeLatestTurn.startedAt, activeLatestTurn.completedAt);
|
||||
return elapsed ? `Worked for ${elapsed}` : null;
|
||||
}, [
|
||||
activeLatestTurn?.completedAt,
|
||||
activeLatestTurn?.startedAt,
|
||||
latestTurnHasToolActivity,
|
||||
latestTurnSettled,
|
||||
]);
|
||||
const completionDividerBeforeEntryId = useMemo(() => {
|
||||
if (!latestTurnSettled) return null;
|
||||
if (!completionSummary) return null;
|
||||
return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn);
|
||||
}, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]);
|
||||
const gitCwd = activeProject
|
||||
? projectScriptCwd({
|
||||
project: { cwd: activeProject.cwd },
|
||||
@@ -3885,12 +3856,10 @@ export default function ChatView(props: ChatViewProps) {
|
||||
key={activeThread.id}
|
||||
isWorking={isWorking}
|
||||
activeTurnInProgress={isWorking || !latestTurnSettled}
|
||||
activeTurnId={activeLatestTurn?.turnId ?? null}
|
||||
activeTurnStartedAt={activeWorkStartedAt}
|
||||
listRef={legendListRef}
|
||||
timelineEntries={timelineEntries}
|
||||
completionDividerBeforeEntryId={completionDividerBeforeEntryId}
|
||||
completionSummary={completionSummary}
|
||||
latestTurn={activeLatestTurn}
|
||||
turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}
|
||||
activeThreadEnvironmentId={activeThread.environmentId}
|
||||
routeThreadKey={routeThreadKey}
|
||||
|
||||
@@ -910,6 +910,12 @@ function ComposerCommandKeyPlugin(props: {
|
||||
if (!props.onCommandKeyDown || !event) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (key === "Enter" && (event.isComposing || event.keyCode === 229)) {
|
||||
event.stopPropagation();
|
||||
return true;
|
||||
}
|
||||
|
||||
const handled = props.onCommandKeyDown(key, event);
|
||||
if (handled) {
|
||||
event.preventDefault();
|
||||
|
||||
@@ -53,6 +53,8 @@ const DIFF_PANEL_UNSAFE_CSS = `
|
||||
[data-file],
|
||||
[data-error-wrapper],
|
||||
[data-virtualizer-buffer] {
|
||||
--diffs-header-font-family: var(--font-sans) !important;
|
||||
--diffs-font-family: var(--font-mono) !important;
|
||||
--diffs-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-light-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
--diffs-dark-bg: color-mix(in srgb, var(--card) 90%, var(--background)) !important;
|
||||
@@ -93,6 +95,37 @@ const DIFF_PANEL_UNSAFE_CSS = `
|
||||
z-index: 4;
|
||||
background-color: color-mix(in srgb, var(--card) 94%, var(--foreground)) !important;
|
||||
border-bottom: 1px solid var(--border) !important;
|
||||
align-items: center !important;
|
||||
font-family: var(--font-sans) !important;
|
||||
font-size: 12px !important;
|
||||
line-height: 1 !important;
|
||||
min-height: 32px !important;
|
||||
padding-block: 6px !important;
|
||||
}
|
||||
|
||||
[data-diffs-header] [data-header-content] {
|
||||
align-items: center !important;
|
||||
line-height: 1 !important;
|
||||
}
|
||||
|
||||
[data-diffs-header] [data-metadata] {
|
||||
align-items: center !important;
|
||||
line-height: 1 !important;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
[data-diffs-header] [data-additions-count],
|
||||
[data-diffs-header] [data-deletions-count] {
|
||||
font-family: var(--font-mono) !important;
|
||||
font-size: 11px !important;
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1 !important;
|
||||
}
|
||||
|
||||
[data-diffs-header] [data-change-icon],
|
||||
[data-diffs-header] [data-rename-icon] {
|
||||
display: block;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
[data-title] {
|
||||
@@ -103,6 +136,7 @@ const DIFF_PANEL_UNSAFE_CSS = `
|
||||
text-decoration: underline;
|
||||
text-decoration-color: transparent;
|
||||
text-underline-offset: 2px;
|
||||
font-family: var(--font-sans) !important;
|
||||
}
|
||||
|
||||
[data-title]:hover {
|
||||
@@ -488,7 +522,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
inferredCheckpointTurnCountByTurnId[summary.turnId] ??
|
||||
"?"}
|
||||
</span>
|
||||
<span className="text-[9px] leading-tight opacity-70">
|
||||
<span className="text-[9px] leading-tight opacity-70 tabular-nums">
|
||||
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
ChevronDownIcon,
|
||||
CloudUploadIcon,
|
||||
ExternalLinkIcon,
|
||||
GitBranchPlusIcon,
|
||||
GitCommitIcon,
|
||||
InfoIcon,
|
||||
LockIcon,
|
||||
@@ -1611,7 +1612,10 @@ export default function GitActionsControl({
|
||||
void initAction.run();
|
||||
}}
|
||||
>
|
||||
{initAction.isPending ? "Initializing..." : "Initialize Git"}
|
||||
<GitBranchPlusIcon className="size-3.5" aria-hidden />
|
||||
<span className="ml-0.5">
|
||||
{initAction.isPending ? "Initializing..." : "Initialize Git"}
|
||||
</span>
|
||||
</Button>
|
||||
) : (
|
||||
<Group aria-label="Git actions" className="shrink-0">
|
||||
|
||||
@@ -30,7 +30,7 @@ export function NoActiveThreadState() {
|
||||
</header>
|
||||
|
||||
<Empty className="flex-1">
|
||||
<div className="w-full max-w-lg rounded-3xl border border-border/55 bg-card/20 px-8 py-12 shadow-sm/5">
|
||||
<div className="w-full max-w-lg px-8 py-12">
|
||||
<EmptyHeader className="max-w-none">
|
||||
<EmptyTitle className="text-foreground text-xl">Pick a thread to continue</EmptyTitle>
|
||||
<EmptyDescription className="mt-2 text-sm text-muted-foreground/78">
|
||||
|
||||
@@ -32,14 +32,14 @@ import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
function stepStatusIcon(status: string): React.ReactNode {
|
||||
if (status === "completed") {
|
||||
return (
|
||||
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-emerald-500/15 text-emerald-500">
|
||||
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-success/10 text-success-foreground">
|
||||
<CheckIcon className="size-3" />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
if (status === "inProgress") {
|
||||
return (
|
||||
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-blue-500/15 text-blue-400">
|
||||
<span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-primary/10 text-primary">
|
||||
<LoaderIcon className="size-3 animate-spin" />
|
||||
</span>
|
||||
);
|
||||
@@ -139,13 +139,14 @@ const PlanSidebar = memo(function PlanSidebar({
|
||||
<div className="flex h-12 shrink-0 items-center justify-between border-b border-border/60 px-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="rounded-md bg-blue-500/10 px-1.5 py-0 text-[10px] font-semibold tracking-wide text-blue-400 uppercase"
|
||||
variant="info"
|
||||
size="sm"
|
||||
className="rounded-md px-1.5 py-0 font-semibold tracking-wide uppercase"
|
||||
>
|
||||
{label}
|
||||
</Badge>
|
||||
{activePlan ? (
|
||||
<span className="text-[11px] text-muted-foreground/60">
|
||||
<span className="text-[11px] text-muted-foreground/60 tabular-nums">
|
||||
{formatTimestamp(activePlan.createdAt, timestampFormat)}
|
||||
</span>
|
||||
) : null}
|
||||
@@ -211,12 +212,12 @@ const PlanSidebar = memo(function PlanSidebar({
|
||||
<div
|
||||
key={`${step.status}:${step.step}`}
|
||||
className={cn(
|
||||
"flex items-start gap-2.5 rounded-lg px-2.5 py-2 transition-colors duration-200",
|
||||
"flex items-center gap-2.5 rounded-lg px-2.5 py-2 transition-colors duration-200",
|
||||
step.status === "inProgress" && "bg-blue-500/5",
|
||||
step.status === "completed" && "bg-emerald-500/5",
|
||||
)}
|
||||
>
|
||||
<div className="mt-0.5">{stepStatusIcon(step.status)}</div>
|
||||
{stepStatusIcon(step.status)}
|
||||
<p
|
||||
className={cn(
|
||||
"text-[13px] leading-snug",
|
||||
|
||||
@@ -10,7 +10,6 @@ import { memo } from "react";
|
||||
import GitActionsControl from "../GitActionsControl";
|
||||
import { type DraftId } from "~/composerDraftStore";
|
||||
import { DiffIcon, TerminalSquareIcon } from "lucide-react";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import ProjectScriptsControl, { type NewProjectScriptInput } from "../ProjectScriptsControl";
|
||||
import { Toggle } from "../ui/toggle";
|
||||
@@ -105,19 +104,6 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
/>
|
||||
<TooltipPopup side="top">{activeThreadTitle}</TooltipPopup>
|
||||
</Tooltip>
|
||||
{activeProjectName && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="min-w-0 max-w-full shrink overflow-hidden sm:max-w-56"
|
||||
>
|
||||
<span className="min-w-0 truncate">{activeProjectName}</span>
|
||||
</Badge>
|
||||
)}
|
||||
{activeProjectName && !isGitRepo && (
|
||||
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
|
||||
No Git
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex min-w-0 flex-wrap items-center justify-start gap-2 sm:shrink-0 sm:justify-end @3xl/header-actions:gap-3">
|
||||
{activeProjectScripts && (
|
||||
@@ -153,7 +139,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
pressed={terminalOpen}
|
||||
onPressedChange={onToggleTerminal}
|
||||
aria-label="Toggle terminal drawer"
|
||||
variant="outline"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
disabled={!terminalAvailable}
|
||||
>
|
||||
@@ -177,7 +163,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
pressed={diffOpen}
|
||||
onPressedChange={onToggleDiff}
|
||||
aria-label="Toggle diff panel"
|
||||
variant="outline"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
disabled={!isGitRepo && !diffOpen}
|
||||
>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { memo } from "react";
|
||||
import { Badge } from "../ui/badge";
|
||||
|
||||
export const ComposerPlanFollowUpBanner = memo(function ComposerPlanFollowUpBanner({
|
||||
planTitle,
|
||||
@@ -8,7 +9,13 @@ export const ComposerPlanFollowUpBanner = memo(function ComposerPlanFollowUpBann
|
||||
return (
|
||||
<div className="px-4 py-3.5 sm:px-5 sm:py-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="uppercase text-sm tracking-[0.2em]">Plan ready</span>
|
||||
<Badge
|
||||
variant="info"
|
||||
size="sm"
|
||||
className="rounded-md px-1.5 py-0 font-semibold tracking-wide uppercase"
|
||||
>
|
||||
Plan Ready
|
||||
</Badge>
|
||||
{planTitle ? (
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium">{planTitle}</span>
|
||||
) : null}
|
||||
|
||||
@@ -68,11 +68,11 @@ export const MessageCopyButton = memo(function MessageCopyButton({
|
||||
type="button"
|
||||
size={size}
|
||||
variant={variant}
|
||||
className={cn(className)}
|
||||
className={cn("text-muted-foreground hover:text-foreground", className)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{isCopied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
|
||||
{isCopied ? <CheckIcon className="size-3 text-primary" /> : <CopyIcon className="size-3" />}
|
||||
</TooltipTrigger>
|
||||
<TooltipPopup>
|
||||
<p>Copy to clipboard</p>
|
||||
|
||||
@@ -7,6 +7,8 @@ import { page } from "vite-plus/test/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { getVscodeIconUrlForEntry } from "../../vscode-icons";
|
||||
|
||||
const scrollToEndSpy = vi.fn();
|
||||
const getStateSpy = vi.fn(() => ({ isAtEnd: true }));
|
||||
|
||||
@@ -52,11 +54,9 @@ function buildProps() {
|
||||
return {
|
||||
isWorking: false,
|
||||
activeTurnInProgress: false,
|
||||
activeTurnId: null,
|
||||
activeTurnStartedAt: null,
|
||||
listRef: createRef<LegendListRef | null>(),
|
||||
completionDividerBeforeEntryId: null,
|
||||
completionSummary: null,
|
||||
latestTurn: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
routeThreadKey: "environment-local:thread-1",
|
||||
onOpenTurnDiff: vi.fn(),
|
||||
@@ -129,9 +129,9 @@ describe("MessagesTimeline", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-04-13T12:00:00.000Z",
|
||||
label: "thinking",
|
||||
label: "read files",
|
||||
detail: "Inspecting repository state",
|
||||
tone: "thinking",
|
||||
tone: "tool",
|
||||
},
|
||||
},
|
||||
]}
|
||||
@@ -142,14 +142,14 @@ describe("MessagesTimeline", () => {
|
||||
await expect
|
||||
.element(page.getByText("Send a message to start the conversation."))
|
||||
.not.toBeInTheDocument();
|
||||
await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible();
|
||||
await expect.element(page.getByText("Inspecting repository state")).toBeVisible();
|
||||
expect(document.querySelector('[data-testid="legend-list"] [title]')).toBeNull();
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("uses accessible tooltips instead of native titles for work entry details", async () => {
|
||||
it("uses accessible expansion instead of native titles or preview tooltips for work entry details", async () => {
|
||||
const screen = await render(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
@@ -181,21 +181,12 @@ describe("MessagesTimeline", () => {
|
||||
"Command - git diff -- apps/web/src/components/ChatMarkdown.tsx",
|
||||
);
|
||||
await commandTrigger.hover();
|
||||
await vi.waitFor(() => {
|
||||
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
|
||||
expect(tooltip?.textContent).toContain(
|
||||
"git diff -- apps/web/src/components/ChatMarkdown.tsx --stat",
|
||||
);
|
||||
});
|
||||
expect(document.querySelector('[data-slot="tooltip-popup"]')).toBeNull();
|
||||
|
||||
const fileTrigger = page.getByLabelText("repo/apps/web/src/components/ChatMarkdown.tsx", {
|
||||
exact: true,
|
||||
});
|
||||
await fileTrigger.hover();
|
||||
await vi.waitFor(() => {
|
||||
const tooltip = document.querySelector<HTMLElement>('[data-slot="tooltip-popup"]');
|
||||
expect(tooltip?.textContent).toContain("apps/web/src/components/ChatMarkdown.tsx");
|
||||
});
|
||||
await commandTrigger.click();
|
||||
await expect
|
||||
.element(page.getByText("git diff -- apps/web/src/components/ChatMarkdown.tsx --stat"))
|
||||
.toBeVisible();
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
@@ -229,16 +220,16 @@ describe("MessagesTimeline", () => {
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-04-13T12:00:00.000Z",
|
||||
label: "thinking",
|
||||
label: "read files",
|
||||
detail: "Inspecting repository state",
|
||||
tone: "thinking",
|
||||
tone: "tool",
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
await expect.element(page.getByText("Thinking - Inspecting repository state")).toBeVisible();
|
||||
await expect.element(page.getByText("Inspecting repository state")).toBeVisible();
|
||||
expect(props.onIsAtEndChange).toHaveBeenCalledWith(true);
|
||||
expect(scrollToEndSpy).toHaveBeenCalledWith({ animated: false });
|
||||
expect(requestAnimationFrameSpy).toHaveBeenCalled();
|
||||
@@ -386,4 +377,105 @@ describe("MessagesTimeline", () => {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the file path without line suffix for markdown file tag icons", async () => {
|
||||
const fileLink = "[package.json](path/to/package.json:25)";
|
||||
const screen = await render(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
markdownCwd="/repo/project"
|
||||
timelineEntries={[buildAssistantTimelineEntry(`Updated ${fileLink}`)]}
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
const assistantFileLink = document.querySelector(
|
||||
'[data-message-role="assistant"] .chat-markdown-file-link',
|
||||
);
|
||||
const icon = assistantFileLink?.querySelector("img");
|
||||
|
||||
expect(assistantFileLink?.textContent).toContain("package.json");
|
||||
expect(assistantFileLink?.textContent).toContain("L25");
|
||||
expect(assistantFileLink?.getAttribute("href")).toBe("/repo/project/path/to/package.json:25");
|
||||
expect(icon?.getAttribute("src")).toBe(
|
||||
getVscodeIconUrlForEntry("/repo/project/path/to/package.json", "file", "dark"),
|
||||
);
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
|
||||
it("folds settled-turn work behind a Worked-for row and expands it on click", async () => {
|
||||
const screen = await render(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-commentary",
|
||||
kind: "message" as const,
|
||||
createdAt: "2026-04-13T12:00:00.000Z",
|
||||
message: {
|
||||
id: "message-commentary" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Let me look around first.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-04-13T12:00:00.000Z",
|
||||
completedAt: "2026-04-13T12:00:02.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "entry-work",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-04-13T12:00:05.000Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-04-13T12:00:05.000Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "read files",
|
||||
detail: "Inspecting repository state",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "entry-final",
|
||||
kind: "message" as const,
|
||||
createdAt: "2026-04-13T12:00:20.000Z",
|
||||
message: {
|
||||
id: "message-final" as never,
|
||||
role: "assistant" as const,
|
||||
text: "All done.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-04-13T12:00:20.000Z",
|
||||
completedAt: "2026-04-13T12:00:30.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
try {
|
||||
const foldButton = page.getByRole("button", { name: "Worked for 30s" });
|
||||
await expect.element(foldButton).toBeVisible();
|
||||
await expect.element(foldButton).toHaveAttribute("aria-expanded", "false");
|
||||
|
||||
expect(document.body.textContent).toContain("All done.");
|
||||
expect(document.body.textContent).not.toContain("Let me look around first.");
|
||||
expect(document.body.textContent).not.toContain("Inspecting repository state");
|
||||
|
||||
await foldButton.click();
|
||||
|
||||
await expect.element(foldButton).toHaveAttribute("aria-expanded", "true");
|
||||
expect(document.body.textContent).toContain("Let me look around first.");
|
||||
expect(document.body.textContent).toContain("Inspecting repository state");
|
||||
|
||||
await foldButton.click();
|
||||
|
||||
await expect.element(foldButton).toHaveAttribute("aria-expanded", "false");
|
||||
expect(document.body.textContent).not.toContain("Inspecting repository state");
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -250,7 +250,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
},
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: "assistant-final-entry",
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
@@ -265,7 +265,6 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
expect(assistantRows).toHaveLength(2);
|
||||
expect(assistantRows[0]?.showAssistantCopyButton).toBe(false);
|
||||
expect(assistantRows[1]?.showAssistantCopyButton).toBe(true);
|
||||
expect(assistantRows[1]?.showCompletionDivider).toBe(true);
|
||||
});
|
||||
|
||||
it("marks only the active assistant turn as streaming for copy controls", () => {
|
||||
@@ -300,11 +299,13 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
},
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: "assistant-two-entry",
|
||||
completionSummary: "done",
|
||||
latestTurn: {
|
||||
turnId: "turn-2" as never,
|
||||
state: "running",
|
||||
startedAt: "2026-01-01T00:00:19Z",
|
||||
completedAt: null,
|
||||
},
|
||||
isWorking: false,
|
||||
activeTurnInProgress: true,
|
||||
activeTurnId: "turn-2" as never,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
@@ -316,9 +317,7 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
);
|
||||
|
||||
expect(assistantRows[0]?.assistantCopyStreaming).toBe(false);
|
||||
expect(assistantRows[0]?.completionSummary).toBeNull();
|
||||
expect(assistantRows[1]?.assistantCopyStreaming).toBe(true);
|
||||
expect(assistantRows[1]?.completionSummary).toBe("done");
|
||||
});
|
||||
|
||||
it("projects assistant diff summaries and user revert counts onto the affected rows", () => {
|
||||
@@ -360,7 +359,6 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
},
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: null,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map([
|
||||
@@ -381,6 +379,441 @@ describe("deriveMessagesTimelineRows", () => {
|
||||
expect(userRow?.revertTurnCount).toBe(1);
|
||||
expect(assistantRow?.assistantTurnDiffSummary).toBe(assistantTurnDiffSummary);
|
||||
});
|
||||
|
||||
it("folds settled-turn commentary and work behind a Worked-for row", () => {
|
||||
const timelineEntries = [
|
||||
{
|
||||
id: "user-entry",
|
||||
kind: "message" as const,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
message: {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "Build it",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-thought-entry",
|
||||
kind: "message" as const,
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
message: {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Looking around first.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
completedAt: "2026-01-01T00:00:06Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "work-entry-1",
|
||||
kind: "work" as const,
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-final-entry",
|
||||
kind: "message" as const,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
message: {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
completedAt: "2026-01-01T00:00:22Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const collapsedRows = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const foldRow = collapsedRows.find(
|
||||
(row): row is Extract<(typeof collapsedRows)[number], { kind: "turn-fold" }> =>
|
||||
row.kind === "turn-fold",
|
||||
);
|
||||
expect(foldRow?.turnId).toBe("turn-1");
|
||||
expect(foldRow?.expanded).toBe(false);
|
||||
// User message boundary (00:00:00) → terminal message completedAt (00:00:22).
|
||||
expect(foldRow?.label).toBe("Worked for 22s");
|
||||
expect(collapsedRows.map((row) => row.id)).toEqual([
|
||||
"user-entry",
|
||||
"turn-fold:turn-1",
|
||||
"assistant-final-entry",
|
||||
]);
|
||||
|
||||
const expandedRows = deriveMessagesTimelineRows({
|
||||
timelineEntries,
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
expect(expandedRows.map((row) => row.id)).toEqual([
|
||||
"user-entry",
|
||||
"turn-fold:turn-1",
|
||||
"assistant-thought-entry",
|
||||
"work-entry-1",
|
||||
"assistant-final-entry",
|
||||
]);
|
||||
expect(
|
||||
expandedRows.find((row) => row.kind === "turn-fold" && row.expanded === true),
|
||||
).toBeDefined();
|
||||
});
|
||||
|
||||
it("derives a sane duration for a steer-superseded turn with one instant commentary message", () => {
|
||||
// A steer ends the previous turn early: its only message completes the
|
||||
// instant it is created, and trailing work entries land after it. The
|
||||
// fold duration must span from the user message that started the turn to
|
||||
// the last entry, not message createdAt → message completedAt (~0ms).
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "user-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
message: {
|
||||
id: "user-1" as never,
|
||||
role: "user" as const,
|
||||
text: "do it once more",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:00Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-commentary-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:09Z",
|
||||
message: {
|
||||
id: "assistant-commentary" as never,
|
||||
role: "assistant" as const,
|
||||
text: "Kicking off call 1.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:09Z",
|
||||
completedAt: "2026-01-01T00:00:09Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "work-entry-1",
|
||||
kind: "work",
|
||||
createdAt: "2026-01-01T00:00:12Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:12Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "steer-user-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:14Z",
|
||||
message: {
|
||||
id: "user-2" as never,
|
||||
role: "user" as const,
|
||||
text: "actually do 15",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:00:14Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-next-turn-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:17Z",
|
||||
message: {
|
||||
id: "assistant-next" as never,
|
||||
role: "assistant" as const,
|
||||
text: "One down — adjusting.",
|
||||
turnId: "turn-2" as never,
|
||||
createdAt: "2026-01-01T00:00:17Z",
|
||||
streaming: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-2" as never,
|
||||
state: "running",
|
||||
startedAt: "2026-01-01T00:00:14Z",
|
||||
completedAt: null,
|
||||
},
|
||||
isWorking: true,
|
||||
activeTurnStartedAt: "2026-01-01T00:00:14Z",
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const foldRow = rows.find(
|
||||
(row): row is Extract<(typeof rows)[number], { kind: "turn-fold" }> =>
|
||||
row.kind === "turn-fold",
|
||||
);
|
||||
// User message (00:00:00) → trailing work entry (00:00:12).
|
||||
expect(foldRow?.turnId).toBe("turn-1");
|
||||
expect(foldRow?.label).toBe("Worked for 12s");
|
||||
});
|
||||
|
||||
it("uses latest-turn timings and the stopped label for an interrupted latest turn", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "work-entry-1",
|
||||
kind: "work",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "interrupted",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: "2026-01-01T00:00:47Z",
|
||||
},
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
expect(rows).toEqual([
|
||||
expect.objectContaining({
|
||||
kind: "turn-fold",
|
||||
turnId: "turn-1",
|
||||
label: "You stopped after 47s",
|
||||
expanded: false,
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the previous turn folded while a newly sent message awaits its turn", () => {
|
||||
// Right after send, isWorking is true but latestTurn still points at the
|
||||
// previous, settled turn — it must stay folded through that window.
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "work-entry-1",
|
||||
kind: "work",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-final-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
message: {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant",
|
||||
text: "Done",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
completedAt: "2026-01-01T00:00:22Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "user-followup-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:01:00Z",
|
||||
message: {
|
||||
id: "user-followup" as never,
|
||||
role: "user",
|
||||
text: "yooo",
|
||||
turnId: null,
|
||||
createdAt: "2026-01-01T00:01:00Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "completed",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: "2026-01-01T00:00:22Z",
|
||||
},
|
||||
isWorking: true,
|
||||
activeTurnStartedAt: "2026-01-01T00:01:00Z",
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
expect(rows.map((row) => row.id)).toEqual([
|
||||
"turn-fold:turn-1",
|
||||
"assistant-final-entry",
|
||||
"user-followup-entry",
|
||||
"working-indicator-row",
|
||||
]);
|
||||
const finalRow = rows.find((row) => row.id === "assistant-final-entry");
|
||||
expect(finalRow?.kind === "message" && finalRow.showAssistantMeta).toBe(true);
|
||||
});
|
||||
|
||||
it("does not fold the active in-progress turn", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "assistant-thought-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
message: {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "Working on it.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
completedAt: "2026-01-01T00:00:06Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "work-entry-1",
|
||||
kind: "work",
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-01-01T00:00:08Z",
|
||||
turnId: "turn-1" as never,
|
||||
label: "Ran command",
|
||||
tone: "tool" as const,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "running",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: null,
|
||||
},
|
||||
isWorking: true,
|
||||
activeTurnStartedAt: "2026-01-01T00:00:00Z",
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
expect(rows.some((row) => row.kind === "turn-fold")).toBe(false);
|
||||
expect(rows.map((row) => row.id)).toEqual([
|
||||
"assistant-thought-entry",
|
||||
"work-entry-1",
|
||||
"working-indicator-row",
|
||||
]);
|
||||
});
|
||||
|
||||
it("only shows assistant metadata on the terminal assistant message", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "assistant-thought-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
message: {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "Checking first.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
completedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "assistant-final-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
message: {
|
||||
id: "assistant-final" as never,
|
||||
role: "assistant",
|
||||
text: "Done.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:20Z",
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
expandedTurnIds: new Set(["turn-1" as never]),
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const assistantRows = rows.filter(
|
||||
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
|
||||
row.kind === "message" && row.message.role === "assistant",
|
||||
);
|
||||
|
||||
expect(assistantRows.map((row) => row.showAssistantMeta)).toEqual([false, true]);
|
||||
});
|
||||
|
||||
it("withholds assistant metadata while the active turn is still in progress", () => {
|
||||
const rows = deriveMessagesTimelineRows({
|
||||
timelineEntries: [
|
||||
{
|
||||
id: "assistant-thought-entry",
|
||||
kind: "message",
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
message: {
|
||||
id: "assistant-thought" as never,
|
||||
role: "assistant",
|
||||
text: "Working on it.",
|
||||
turnId: "turn-1" as never,
|
||||
createdAt: "2026-01-01T00:00:10Z",
|
||||
completedAt: "2026-01-01T00:00:11Z",
|
||||
streaming: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
latestTurn: {
|
||||
turnId: "turn-1" as never,
|
||||
state: "running",
|
||||
startedAt: "2026-01-01T00:00:00Z",
|
||||
completedAt: null,
|
||||
},
|
||||
isWorking: true,
|
||||
activeTurnStartedAt: "2026-01-01T00:00:00Z",
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
revertTurnCountByUserMessageId: new Map(),
|
||||
});
|
||||
|
||||
const assistantRow = rows.find(
|
||||
(row): row is Extract<(typeof rows)[number], { kind: "message" }> =>
|
||||
row.kind === "message" && row.message.role === "assistant",
|
||||
);
|
||||
|
||||
expect(assistantRow?.showAssistantMeta).toBe(false);
|
||||
expect(assistantRow?.showAssistantCopyButton).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("computeStableMessagesTimelineRows", () => {
|
||||
@@ -417,7 +850,6 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
message: secondUserMessage,
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: null,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
@@ -467,7 +899,6 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
entry: secondWorkEntry,
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: null,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
@@ -522,7 +953,6 @@ describe("computeStableMessagesTimelineRows", () => {
|
||||
message: secondUserMessage,
|
||||
},
|
||||
],
|
||||
completionDividerBeforeEntryId: null,
|
||||
isWorking: false,
|
||||
activeTurnStartedAt: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
|
||||
@@ -1,9 +1,26 @@
|
||||
import * as Equal from "effect/Equal";
|
||||
import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";
|
||||
import { formatDuration, type TimelineEntry, type WorkLogEntry } from "../../session-logic";
|
||||
import { type ChatMessage, type ProposedPlan, type TurnDiffSummary } from "../../types";
|
||||
import { type MessageId, type TurnId } from "@t3tools/contracts";
|
||||
import { type MessageId, type OrchestrationLatestTurn, type TurnId } from "@t3tools/contracts";
|
||||
|
||||
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
export const MAX_VISIBLE_WORK_LOG_ENTRIES = 1;
|
||||
|
||||
function computeElapsedMs(startIso: string, endIso: string): number | null {
|
||||
const start = Date.parse(startIso);
|
||||
const end = Date.parse(endIso);
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end)) return null;
|
||||
return Math.max(0, end - start);
|
||||
}
|
||||
|
||||
function maxIsoTimestamp(a: string | null, b: string | null): string | null {
|
||||
if (a === null) return b;
|
||||
if (b === null) return a;
|
||||
const aMs = Date.parse(a);
|
||||
const bMs = Date.parse(b);
|
||||
if (!Number.isFinite(aMs)) return b;
|
||||
if (!Number.isFinite(bMs)) return a;
|
||||
return bMs > aMs ? b : a;
|
||||
}
|
||||
|
||||
export interface TimelineDurationMessage {
|
||||
id: string;
|
||||
@@ -12,6 +29,11 @@ export interface TimelineDurationMessage {
|
||||
completedAt?: string | undefined;
|
||||
}
|
||||
|
||||
export type TimelineLatestTurn = Pick<
|
||||
OrchestrationLatestTurn,
|
||||
"turnId" | "state" | "startedAt" | "completedAt"
|
||||
>;
|
||||
|
||||
export type MessagesTimelineRow =
|
||||
| {
|
||||
kind: "work";
|
||||
@@ -19,14 +41,21 @@ export type MessagesTimelineRow =
|
||||
createdAt: string;
|
||||
groupedEntries: WorkLogEntry[];
|
||||
}
|
||||
| {
|
||||
kind: "turn-fold";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
turnId: TurnId;
|
||||
label: string;
|
||||
expanded: boolean;
|
||||
}
|
||||
| {
|
||||
kind: "message";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
message: ChatMessage;
|
||||
durationStart: string;
|
||||
showCompletionDivider: boolean;
|
||||
completionSummary: string | null;
|
||||
showAssistantMeta: boolean;
|
||||
showAssistantCopyButton: boolean;
|
||||
assistantCopyStreaming: boolean;
|
||||
assistantTurnDiffSummary?: TurnDiffSummary | undefined;
|
||||
@@ -110,13 +139,161 @@ function deriveTerminalAssistantMessageIds(timelineEntries: ReadonlyArray<Timeli
|
||||
return new Set(lastAssistantMessageIdByResponseKey.values());
|
||||
}
|
||||
|
||||
interface TurnFold {
|
||||
turnId: TurnId;
|
||||
anchorEntryId: string;
|
||||
createdAt: string;
|
||||
hiddenEntryIds: ReadonlySet<string>;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The latest turn counts as unsettled while it is still running (or has not
|
||||
* recorded a completion). This is deliberately keyed on the turn's own
|
||||
* lifecycle rather than transient working state: right after the user sends
|
||||
* a message, the previous turn is still the "active" one until the server
|
||||
* creates the new turn, and folding must not flicker through that window.
|
||||
*/
|
||||
function deriveUnsettledTurnId(latestTurn: TimelineLatestTurn | null): TurnId | null {
|
||||
if (!latestTurn) {
|
||||
return null;
|
||||
}
|
||||
const isSettled = latestTurn.completedAt !== null && latestTurn.state !== "running";
|
||||
return isSettled ? null : latestTurn.turnId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Settled turns fold their commentary and tool activity behind a
|
||||
* "Worked for ..." row anchored at the turn's first foldable entry; the
|
||||
* terminal assistant message stays visible below the fold.
|
||||
*/
|
||||
function deriveTurnFolds(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
terminalAssistantMessageIds: ReadonlySet<string>;
|
||||
latestTurn: TimelineLatestTurn | null;
|
||||
unsettledTurnId: TurnId | null;
|
||||
}): ReadonlyMap<string, TurnFold> {
|
||||
interface TurnGroup {
|
||||
entries: Array<TimelineEntry>;
|
||||
terminalEntry: Extract<TimelineEntry, { kind: "message" }> | null;
|
||||
hasStreamingMessage: boolean;
|
||||
/**
|
||||
* The user message that kicked the turn off. Entry timestamps alone
|
||||
* undercount the duration (the first entry appears only once the
|
||||
* provider starts producing output), and a turn cut short by a steer may
|
||||
* hold a single instantaneous commentary message.
|
||||
*/
|
||||
startBoundary: string | null;
|
||||
}
|
||||
const groupsByTurnId = new Map<TurnId, TurnGroup>();
|
||||
|
||||
let pendingUserBoundary: string | null = null;
|
||||
for (const entry of input.timelineEntries) {
|
||||
if (entry.kind === "message" && entry.message.role === "user") {
|
||||
pendingUserBoundary = entry.message.createdAt;
|
||||
continue;
|
||||
}
|
||||
const turnId =
|
||||
entry.kind === "message" && entry.message.role === "assistant"
|
||||
? (entry.message.turnId ?? null)
|
||||
: entry.kind === "work"
|
||||
? (entry.entry.turnId ?? null)
|
||||
: null;
|
||||
if (!turnId) {
|
||||
continue;
|
||||
}
|
||||
let group = groupsByTurnId.get(turnId);
|
||||
if (!group) {
|
||||
group = {
|
||||
entries: [],
|
||||
terminalEntry: null,
|
||||
hasStreamingMessage: false,
|
||||
// Each user boundary starts at most one turn; a second turn after the
|
||||
// same user message (e.g. a steer-superseded continuation) falls back
|
||||
// to its own first entry.
|
||||
startBoundary: pendingUserBoundary,
|
||||
};
|
||||
pendingUserBoundary = null;
|
||||
groupsByTurnId.set(turnId, group);
|
||||
}
|
||||
group.entries.push(entry);
|
||||
if (entry.kind === "message") {
|
||||
if (input.terminalAssistantMessageIds.has(entry.message.id)) {
|
||||
group.terminalEntry = entry;
|
||||
}
|
||||
if (entry.message.streaming) {
|
||||
group.hasStreamingMessage = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const foldsByAnchorEntryId = new Map<string, TurnFold>();
|
||||
for (const [turnId, group] of groupsByTurnId) {
|
||||
if (turnId === input.unsettledTurnId) {
|
||||
continue;
|
||||
}
|
||||
if (group.hasStreamingMessage) {
|
||||
continue;
|
||||
}
|
||||
const hiddenEntryIds = new Set<string>();
|
||||
for (const entry of group.entries) {
|
||||
if (entry.id !== group.terminalEntry?.id) {
|
||||
hiddenEntryIds.add(entry.id);
|
||||
}
|
||||
}
|
||||
if (hiddenEntryIds.size === 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const firstEntry = group.entries[0];
|
||||
const lastEntry = group.entries.at(-1);
|
||||
if (!firstEntry || !lastEntry) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const isLatestInterruptedTurn =
|
||||
input.latestTurn?.turnId === turnId && input.latestTurn.state === "interrupted";
|
||||
// A turn cut short by a steer leaves trailing work entries behind its
|
||||
// terminal message — take whichever ended last.
|
||||
const lastEntryEnd =
|
||||
lastEntry.kind === "message"
|
||||
? (lastEntry.message.completedAt ?? lastEntry.createdAt)
|
||||
: lastEntry.createdAt;
|
||||
const elapsedMs =
|
||||
input.latestTurn?.turnId === turnId &&
|
||||
input.latestTurn.startedAt &&
|
||||
input.latestTurn.completedAt
|
||||
? computeElapsedMs(input.latestTurn.startedAt, input.latestTurn.completedAt)
|
||||
: computeElapsedMs(
|
||||
group.startBoundary ?? firstEntry.createdAt,
|
||||
maxIsoTimestamp(group.terminalEntry?.message.completedAt ?? null, lastEntryEnd) ??
|
||||
lastEntryEnd,
|
||||
);
|
||||
const duration = elapsedMs !== null ? formatDuration(elapsedMs) : null;
|
||||
const label = isLatestInterruptedTurn
|
||||
? duration
|
||||
? `You stopped after ${duration}`
|
||||
: "You stopped this response"
|
||||
: duration
|
||||
? `Worked for ${duration}`
|
||||
: "Worked";
|
||||
|
||||
foldsByAnchorEntryId.set(firstEntry.id, {
|
||||
turnId,
|
||||
anchorEntryId: firstEntry.id,
|
||||
createdAt: firstEntry.createdAt,
|
||||
hiddenEntryIds,
|
||||
label,
|
||||
});
|
||||
}
|
||||
return foldsByAnchorEntryId;
|
||||
}
|
||||
|
||||
export function deriveMessagesTimelineRows(input: {
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>;
|
||||
completionDividerBeforeEntryId: string | null;
|
||||
completionSummary?: string | null;
|
||||
latestTurn?: TimelineLatestTurn | null;
|
||||
expandedTurnIds?: ReadonlySet<TurnId>;
|
||||
isWorking: boolean;
|
||||
activeTurnInProgress?: boolean;
|
||||
activeTurnId?: TurnId | null;
|
||||
activeTurnStartedAt: string | null;
|
||||
turnDiffSummaryByAssistantMessageId: ReadonlyMap<MessageId, TurnDiffSummary>;
|
||||
revertTurnCountByUserMessageId: ReadonlyMap<MessageId, number>;
|
||||
@@ -126,6 +303,21 @@ export function deriveMessagesTimelineRows(input: {
|
||||
input.timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
|
||||
);
|
||||
const terminalAssistantMessageIds = deriveTerminalAssistantMessageIds(input.timelineEntries);
|
||||
const unsettledTurnId = deriveUnsettledTurnId(input.latestTurn ?? null);
|
||||
const foldsByAnchorEntryId = deriveTurnFolds({
|
||||
timelineEntries: input.timelineEntries,
|
||||
terminalAssistantMessageIds,
|
||||
latestTurn: input.latestTurn ?? null,
|
||||
unsettledTurnId,
|
||||
});
|
||||
const collapsedEntryIds = new Set<string>();
|
||||
for (const fold of foldsByAnchorEntryId.values()) {
|
||||
if (!input.expandedTurnIds?.has(fold.turnId)) {
|
||||
for (const entryId of fold.hiddenEntryIds) {
|
||||
collapsedEntryIds.add(entryId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let index = 0; index < input.timelineEntries.length; index += 1) {
|
||||
const timelineEntry = input.timelineEntries[index];
|
||||
@@ -133,12 +325,35 @@ export function deriveMessagesTimelineRows(input: {
|
||||
continue;
|
||||
}
|
||||
|
||||
const turnFold = foldsByAnchorEntryId.get(timelineEntry.id);
|
||||
if (turnFold) {
|
||||
nextRows.push({
|
||||
kind: "turn-fold",
|
||||
id: `turn-fold:${turnFold.turnId}`,
|
||||
createdAt: turnFold.createdAt,
|
||||
turnId: turnFold.turnId,
|
||||
label: turnFold.label,
|
||||
expanded: input.expandedTurnIds?.has(turnFold.turnId) ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
if (collapsedEntryIds.has(timelineEntry.id)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (timelineEntry.kind === "work") {
|
||||
const groupedEntries = [timelineEntry.entry];
|
||||
let cursor = index + 1;
|
||||
while (cursor < input.timelineEntries.length) {
|
||||
const nextEntry = input.timelineEntries[cursor];
|
||||
if (!nextEntry || nextEntry.kind !== "work") break;
|
||||
if (
|
||||
!nextEntry ||
|
||||
nextEntry.kind !== "work" ||
|
||||
collapsedEntryIds.has(nextEntry.id) ||
|
||||
foldsByAnchorEntryId.has(nextEntry.id)
|
||||
) {
|
||||
break;
|
||||
}
|
||||
groupedEntries.push(nextEntry.entry);
|
||||
cursor += 1;
|
||||
}
|
||||
@@ -164,26 +379,28 @@ export function deriveMessagesTimelineRows(input: {
|
||||
|
||||
const assistantTurnStillInProgress =
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
input.activeTurnInProgress === true &&
|
||||
input.activeTurnId != null &&
|
||||
timelineEntry.message.turnId === input.activeTurnId;
|
||||
unsettledTurnId !== null &&
|
||||
timelineEntry.message.turnId === unsettledTurnId;
|
||||
|
||||
const showCompletionDivider =
|
||||
const durationStart =
|
||||
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt;
|
||||
|
||||
// While the turn is still running, the latest assistant message is only
|
||||
// provisionally terminal — withhold the metadata row until the turn
|
||||
// settles so commentary doesn't flash timestamps mid-work.
|
||||
const showAssistantMeta =
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
input.completionDividerBeforeEntryId === timelineEntry.id;
|
||||
terminalAssistantMessageIds.has(timelineEntry.message.id) &&
|
||||
!assistantTurnStillInProgress;
|
||||
|
||||
nextRows.push({
|
||||
kind: "message",
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
message: timelineEntry.message,
|
||||
durationStart:
|
||||
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
|
||||
showCompletionDivider,
|
||||
completionSummary: showCompletionDivider ? (input.completionSummary ?? null) : null,
|
||||
showAssistantCopyButton:
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
terminalAssistantMessageIds.has(timelineEntry.message.id),
|
||||
durationStart,
|
||||
showAssistantMeta,
|
||||
showAssistantCopyButton: showAssistantMeta,
|
||||
assistantCopyStreaming: timelineEntry.message.streaming || assistantTurnStillInProgress,
|
||||
assistantTurnDiffSummary:
|
||||
timelineEntry.message.role === "assistant"
|
||||
@@ -235,6 +452,11 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
case "working":
|
||||
return a.createdAt === (b as typeof a).createdAt;
|
||||
|
||||
case "turn-fold": {
|
||||
const bf = b as typeof a;
|
||||
return a.createdAt === bf.createdAt && a.label === bf.label && a.expanded === bf.expanded;
|
||||
}
|
||||
|
||||
case "proposed-plan":
|
||||
return a.proposedPlan === (b as typeof a).proposedPlan;
|
||||
|
||||
@@ -246,8 +468,7 @@ function isRowUnchanged(a: MessagesTimelineRow, b: MessagesTimelineRow): boolean
|
||||
return (
|
||||
a.message === bm.message &&
|
||||
a.durationStart === bm.durationStart &&
|
||||
a.showCompletionDivider === bm.showCompletionDivider &&
|
||||
a.completionSummary === bm.completionSummary &&
|
||||
a.showAssistantMeta === bm.showAssistantMeta &&
|
||||
a.showAssistantCopyButton === bm.showAssistantCopyButton &&
|
||||
a.assistantCopyStreaming === bm.assistantCopyStreaming &&
|
||||
a.assistantTurnDiffSummary === bm.assistantTurnDiffSummary &&
|
||||
|
||||
@@ -94,11 +94,9 @@ function buildProps() {
|
||||
return {
|
||||
isWorking: false,
|
||||
activeTurnInProgress: false,
|
||||
activeTurnId: null,
|
||||
activeTurnStartedAt: null,
|
||||
listRef: createRef<LegendListRef | null>(),
|
||||
completionDividerBeforeEntryId: null,
|
||||
completionSummary: null,
|
||||
latestTurn: null,
|
||||
turnDiffSummaryByAssistantMessageId: new Map(),
|
||||
routeThreadKey: "environment-local:thread-1",
|
||||
onOpenTurnDiff: () => {},
|
||||
@@ -229,7 +227,7 @@ describe("MessagesTimeline", () => {
|
||||
);
|
||||
|
||||
expect(markup).toContain("Context compacted");
|
||||
expect(markup).toContain("Work log");
|
||||
expect(markup).toContain("work log");
|
||||
});
|
||||
|
||||
it("formats changed file paths from the workspace root", async () => {
|
||||
@@ -297,4 +295,31 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).not.toContain("<review_comment");
|
||||
expect(markup).not.toContain("</review_comment>");
|
||||
});
|
||||
|
||||
it("renders a failure marker for failed tool lifecycle entries", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
{...buildProps()}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-1",
|
||||
kind: "work",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
label: "Glob",
|
||||
tone: "tool",
|
||||
toolLifecycleStatus: "failed",
|
||||
detail: "No files found",
|
||||
},
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("lucide-x");
|
||||
expect(markup).toContain('aria-label="Tool call failed"');
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -12,7 +12,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import * as Arr from "effect/Array";
|
||||
import * as Result from "effect/Result";
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { useState, type ReactNode } from "react";
|
||||
import {
|
||||
isProviderDriverKind,
|
||||
type ProviderInstanceConfig,
|
||||
@@ -77,6 +77,19 @@ function makeEnvironmentDraftRow(
|
||||
};
|
||||
}
|
||||
|
||||
function getProviderEnvironmentSectionKey(
|
||||
environment: ReadonlyArray<ProviderInstanceEnvironmentVariable>,
|
||||
): string {
|
||||
return JSON.stringify(
|
||||
environment.map((variable) => [
|
||||
variable.name,
|
||||
variable.value,
|
||||
variable.sensitive,
|
||||
variable.valueRedacted ?? null,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a string[] at `key` from the opaque config blob, filtering out
|
||||
* non-string entries. Used for `customModels`, which is always typed as
|
||||
@@ -161,10 +174,6 @@ function ProviderEnvironmentSection(props: {
|
||||
props.environment.map(makeEnvironmentDraftRow),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setRows(props.environment.map(makeEnvironmentDraftRow));
|
||||
}, [props.environment]);
|
||||
|
||||
const publishRows = (nextRows: ReadonlyArray<EnvironmentDraftRow>) => {
|
||||
const published: ProviderInstanceEnvironmentVariable[] = [];
|
||||
for (const row of nextRows) {
|
||||
@@ -448,6 +457,8 @@ export function ProviderInstanceCard({
|
||||
: null;
|
||||
|
||||
const customModels = readConfigStringArray(instance.config, "customModels");
|
||||
const environment = instance.environment ?? [];
|
||||
const environmentSectionKey = getProviderEnvironmentSectionKey(environment);
|
||||
// Server-returned models may lag behind settings writes. Treat probe
|
||||
// models as the source for built-ins only; custom rows come directly
|
||||
// from the current instance config so add/remove reflects immediately.
|
||||
@@ -763,7 +774,8 @@ export function ProviderInstanceCard({
|
||||
|
||||
<div className="border-t border-border/60 px-4 py-3 sm:px-5">
|
||||
<ProviderEnvironmentSection
|
||||
environment={instance.environment ?? []}
|
||||
key={environmentSectionKey}
|
||||
environment={environment}
|
||||
onChange={updateEnvironment}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -21,6 +21,8 @@ const toggleVariants = cva(
|
||||
},
|
||||
variant: {
|
||||
default: "border-transparent",
|
||||
ghost:
|
||||
"border-transparent text-foreground shadow-none [:disabled,:active,[data-pressed]]:shadow-none before:shadow-none data-pressed:bg-accent data-pressed:text-accent-foreground disabled:opacity-100 disabled:text-muted-foreground disabled:[&_svg]:opacity-100",
|
||||
outline:
|
||||
"border-input bg-background not-dark:bg-clip-padding shadow-xs/5 not-disabled:not-active:not-data-pressed:before:shadow-[0_1px_--theme(--color-black/4%)] dark:bg-input/32 dark:data-pressed:bg-input dark:hover:bg-input/64 dark:not-disabled:not-active:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/6%)] dark:not-disabled:not-data-pressed:before:shadow-[0_-1px_--theme(--color-white/2%)] [:disabled,:active,[data-pressed]]:shadow-none",
|
||||
},
|
||||
|
||||
+219
-114
@@ -8,7 +8,6 @@ import {
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
deriveCompletionDividerBeforeEntryId,
|
||||
deriveActiveWorkStartedAt,
|
||||
deriveActivePlanState,
|
||||
derivePendingApprovals,
|
||||
@@ -18,8 +17,10 @@ import {
|
||||
findLatestProposedPlan,
|
||||
findSidebarProposedPlan,
|
||||
hasActionableProposedPlan,
|
||||
hasToolActivityForTurn,
|
||||
isLatestTurnSettled,
|
||||
workEntryIndicatesToolFailure,
|
||||
workEntryIndicatesToolNeutralStatus,
|
||||
workEntryIndicatesToolSuccess,
|
||||
} from "./session-logic";
|
||||
|
||||
let nextActivityId = 0;
|
||||
@@ -299,7 +300,7 @@ describe("derivePendingUserInputs", () => {
|
||||
payload: {
|
||||
requestId: "req-user-input-stale-1",
|
||||
detail:
|
||||
"Stale pending user-input request: req-user-input-stale-1. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.",
|
||||
"Provider adapter request failed (codex) for item/tool/requestUserInput: Unknown pending Codex user input request: req-user-input-stale-1",
|
||||
},
|
||||
}),
|
||||
];
|
||||
@@ -572,6 +573,123 @@ describe("findSidebarProposedPlan", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("workEntryIndicatesToolFailure", () => {
|
||||
const base = {
|
||||
id: "w1",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
label: "Read",
|
||||
};
|
||||
|
||||
it("is true for error tone", () => {
|
||||
expect(
|
||||
workEntryIndicatesToolFailure({
|
||||
...base,
|
||||
tone: "error",
|
||||
detail: "nothing special",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("is true when lifecycle says failed even if detail is empty", () => {
|
||||
expect(
|
||||
workEntryIndicatesToolFailure({
|
||||
...base,
|
||||
tone: "tool",
|
||||
toolLifecycleStatus: "failed",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("detects file-not-found style tool output with completed lifecycle", () => {
|
||||
expect(
|
||||
workEntryIndicatesToolFailure({
|
||||
...base,
|
||||
tone: "tool",
|
||||
toolLifecycleStatus: "completed",
|
||||
detail: "File not found: C:\\foo\\nonexistent.ts",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("detects glob no files and PowerShell command errors", () => {
|
||||
expect(
|
||||
workEntryIndicatesToolFailure({
|
||||
...base,
|
||||
label: "Glob",
|
||||
tone: "tool",
|
||||
detail: "No files found",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
workEntryIndicatesToolFailure({
|
||||
...base,
|
||||
label: "Bash",
|
||||
tone: "tool",
|
||||
detail:
|
||||
"The term 'this_is_not_a_command' is not recognized as the name of a cmdlet, function, script file, or operable program.",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("is false for successful completed tools", () => {
|
||||
expect(
|
||||
workEntryIndicatesToolFailure({
|
||||
...base,
|
||||
tone: "tool",
|
||||
toolLifecycleStatus: "completed",
|
||||
detail: "Found 3 matching files",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("treats successful tool rows as success candidates", () => {
|
||||
expect(
|
||||
workEntryIndicatesToolSuccess({
|
||||
...base,
|
||||
tone: "tool",
|
||||
toolLifecycleStatus: "completed",
|
||||
detail: "ok",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
workEntryIndicatesToolSuccess({
|
||||
...base,
|
||||
tone: "tool",
|
||||
toolLifecycleStatus: "inProgress",
|
||||
detail: "…",
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(workEntryIndicatesToolSuccess({ ...base, tone: "thinking", detail: "…" })).toBe(false);
|
||||
expect(
|
||||
workEntryIndicatesToolNeutralStatus({
|
||||
...base,
|
||||
tone: "tool",
|
||||
toolLifecycleStatus: "inProgress",
|
||||
detail: "…",
|
||||
}),
|
||||
).toBe(true);
|
||||
expect(
|
||||
workEntryIndicatesToolNeutralStatus({
|
||||
...base,
|
||||
tone: "tool",
|
||||
toolLifecycleStatus: "completed",
|
||||
detail: "ok",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("does not run heuristics on non-tool info rows", () => {
|
||||
expect(
|
||||
workEntryIndicatesToolFailure({
|
||||
...base,
|
||||
label: "Context compacted",
|
||||
tone: "info",
|
||||
detail: "File not found in conversation",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveWorkLogEntries", () => {
|
||||
it("omits tool started entries and keeps completed entries", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
@@ -589,7 +707,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
|
||||
});
|
||||
|
||||
@@ -618,7 +736,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["task-progress", "task-complete"]);
|
||||
});
|
||||
|
||||
@@ -634,7 +752,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
expect(entries[0]?.label).toBe("Searching for API endpoints");
|
||||
});
|
||||
|
||||
@@ -650,25 +768,33 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
expect(entries[0]?.label).toBe("Failed to deploy changes");
|
||||
expect(entries[0]?.tone).toBe("error");
|
||||
});
|
||||
|
||||
it("filters by turn id when provided", () => {
|
||||
it("keeps tool entries from every turn and tags each with its turn id", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({ id: "turn-1", turnId: "turn-1", summary: "Tool call", kind: "tool.started" }),
|
||||
makeActivity({
|
||||
id: "turn-2",
|
||||
id: "turn-1-tool",
|
||||
turnId: "turn-1",
|
||||
summary: "Tool call complete",
|
||||
kind: "tool.completed",
|
||||
}),
|
||||
makeActivity({
|
||||
id: "turn-2-tool",
|
||||
turnId: "turn-2",
|
||||
summary: "Tool call complete",
|
||||
kind: "tool.completed",
|
||||
}),
|
||||
makeActivity({ id: "no-turn", summary: "Checkpoint captured", tone: "info" }),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, TurnId.make("turn-2"));
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["turn-2"]);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["turn-1-tool", "turn-2-tool"]);
|
||||
expect(entries.map((entry) => entry.turnId)).toEqual([
|
||||
TurnId.make("turn-1"),
|
||||
TurnId.make("turn-2"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("omits checkpoint captured info entries", () => {
|
||||
@@ -688,7 +814,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["tool-complete"]);
|
||||
});
|
||||
|
||||
@@ -724,7 +850,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["real-work-log"]);
|
||||
});
|
||||
|
||||
@@ -746,7 +872,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["first", "second"]);
|
||||
});
|
||||
|
||||
@@ -767,10 +893,47 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry?.command).toBe("bun run lint");
|
||||
});
|
||||
|
||||
it("extracts failed tool lifecycle status from item payloads", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "tool-failed",
|
||||
kind: "tool.updated",
|
||||
summary: "Glob",
|
||||
tone: "tool",
|
||||
payload: {
|
||||
itemType: "mcp_tool_call",
|
||||
status: "failed",
|
||||
detail: "No files found",
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry?.toolLifecycleStatus).toBe("failed");
|
||||
});
|
||||
|
||||
it("defaults tool.completed entries to completed lifecycle status", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
id: "tool-done",
|
||||
kind: "tool.completed",
|
||||
summary: "Glob",
|
||||
tone: "tool",
|
||||
payload: {
|
||||
itemType: "mcp_tool_call",
|
||||
detail: "Found 3 files",
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry?.toolLifecycleStatus).toBe("completed");
|
||||
});
|
||||
|
||||
it("unwraps PowerShell command wrappers for displayed command text", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({
|
||||
@@ -788,7 +951,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry?.command).toBe("bun run lint");
|
||||
expect(entry?.rawCommand).toBe(
|
||||
"\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'bun run lint'",
|
||||
@@ -812,7 +975,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry?.command).toBe("rg -n foo .");
|
||||
expect(entry?.rawCommand).toBe(
|
||||
'"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -Command "rg -n foo ."',
|
||||
@@ -833,7 +996,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry?.command).toBe('rg -n -F "new Date()" .');
|
||||
expect(entry?.rawCommand).toBe(
|
||||
`"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoLogo -NoProfile -Command 'rg -n -F "new Date()" .'`,
|
||||
@@ -857,7 +1020,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry?.command).toBe("bash script.sh");
|
||||
expect(entry?.rawCommand).toBeUndefined();
|
||||
});
|
||||
@@ -886,7 +1049,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry).toMatchObject({
|
||||
command: "bun run dev",
|
||||
detail: '{ "dev": "vite dev --port 3000" }',
|
||||
@@ -915,7 +1078,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry?.changedFiles).toEqual([
|
||||
"apps/web/src/components/ChatView.tsx",
|
||||
"apps/web/src/session-logic.ts",
|
||||
@@ -936,7 +1099,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry?.toolTitle).toBe("Read File");
|
||||
expect(entry?.detail).toBeUndefined();
|
||||
});
|
||||
@@ -980,7 +1143,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
id: "grep-complete",
|
||||
@@ -1029,7 +1192,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
id: "read-complete",
|
||||
@@ -1063,7 +1226,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const [entry] = deriveWorkLogEntries(activities, undefined);
|
||||
const [entry] = deriveWorkLogEntries(activities);
|
||||
expect(entry).toMatchObject({
|
||||
id: "cursor-command-complete",
|
||||
label: "Ran command",
|
||||
@@ -1105,7 +1268,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
id: "legacy-read-complete",
|
||||
@@ -1157,7 +1320,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]).toMatchObject({
|
||||
@@ -1219,7 +1382,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
|
||||
expect(entries.map((entry) => entry.id)).toEqual(["tool-1-complete", "tool-2-complete"]);
|
||||
});
|
||||
@@ -1261,7 +1424,7 @@ describe("deriveWorkLogEntries", () => {
|
||||
}),
|
||||
];
|
||||
|
||||
const entries = deriveWorkLogEntries(activities, undefined);
|
||||
const entries = deriveWorkLogEntries(activities);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.id).toBe("a-complete-same-timestamp");
|
||||
@@ -1311,105 +1474,47 @@ describe("deriveTimelineEntries", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("anchors the completion divider to latestTurn.assistantMessageId before timestamp fallback", () => {
|
||||
const entries = deriveTimelineEntries(
|
||||
[
|
||||
{
|
||||
id: MessageId.make("assistant-earlier"),
|
||||
role: "assistant",
|
||||
text: "progress update",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
{
|
||||
id: MessageId.make("assistant-final"),
|
||||
role: "assistant",
|
||||
text: "final answer",
|
||||
createdAt: "2026-02-23T00:00:01.000Z",
|
||||
streaming: false,
|
||||
},
|
||||
],
|
||||
[],
|
||||
[],
|
||||
);
|
||||
|
||||
expect(
|
||||
deriveCompletionDividerBeforeEntryId(entries, {
|
||||
assistantMessageId: MessageId.make("assistant-final"),
|
||||
startedAt: "2026-02-23T00:00:00.000Z",
|
||||
completedAt: "2026-02-23T00:00:02.000Z",
|
||||
}),
|
||||
).toBe("assistant-final");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveWorkLogEntries context window handling", () => {
|
||||
it("excludes context window updates from the work log", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeActivity({
|
||||
id: "context-1",
|
||||
turnId: "turn-1",
|
||||
kind: "context-window.updated",
|
||||
summary: "Context window updated",
|
||||
tone: "info",
|
||||
}),
|
||||
makeActivity({
|
||||
id: "tool-1",
|
||||
turnId: "turn-1",
|
||||
kind: "tool.completed",
|
||||
summary: "Ran command",
|
||||
tone: "tool",
|
||||
}),
|
||||
],
|
||||
TurnId.make("turn-1"),
|
||||
);
|
||||
const entries = deriveWorkLogEntries([
|
||||
makeActivity({
|
||||
id: "context-1",
|
||||
turnId: "turn-1",
|
||||
kind: "context-window.updated",
|
||||
summary: "Context window updated",
|
||||
tone: "info",
|
||||
}),
|
||||
makeActivity({
|
||||
id: "tool-1",
|
||||
turnId: "turn-1",
|
||||
kind: "tool.completed",
|
||||
summary: "Ran command",
|
||||
tone: "tool",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.label).toBe("Ran command");
|
||||
});
|
||||
|
||||
it("keeps context compaction activities as normal work log entries", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeActivity({
|
||||
id: "compaction-1",
|
||||
turnId: "turn-1",
|
||||
kind: "context-compaction",
|
||||
summary: "Context compacted",
|
||||
tone: "info",
|
||||
}),
|
||||
],
|
||||
TurnId.make("turn-1"),
|
||||
);
|
||||
const entries = deriveWorkLogEntries([
|
||||
makeActivity({
|
||||
id: "compaction-1",
|
||||
turnId: "turn-1",
|
||||
kind: "context-compaction",
|
||||
summary: "Context compacted",
|
||||
tone: "info",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.label).toBe("Context compacted");
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasToolActivityForTurn", () => {
|
||||
it("returns false when turn id is missing", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
|
||||
];
|
||||
|
||||
expect(hasToolActivityForTurn(activities, undefined)).toBe(false);
|
||||
expect(hasToolActivityForTurn(activities, null)).toBe(false);
|
||||
});
|
||||
|
||||
it("returns true only for matching tool activity in the target turn", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
|
||||
makeActivity({ id: "info-1", turnId: "turn-2", kind: "turn.completed", tone: "info" }),
|
||||
];
|
||||
|
||||
expect(hasToolActivityForTurn(activities, TurnId.make("turn-1"))).toBe(true);
|
||||
expect(hasToolActivityForTurn(activities, TurnId.make("turn-2"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isLatestTurnSettled", () => {
|
||||
const latestTurn = {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
|
||||
+176
-62
@@ -53,9 +53,17 @@ export const PROVIDER_OPTIONS: Array<{
|
||||
},
|
||||
];
|
||||
|
||||
export type WorkLogToolLifecycleStatus =
|
||||
| "inProgress"
|
||||
| "completed"
|
||||
| "failed"
|
||||
| "declined"
|
||||
| "stopped";
|
||||
|
||||
export interface WorkLogEntry {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
turnId?: TurnId | null;
|
||||
label: string;
|
||||
detail?: string;
|
||||
command?: string;
|
||||
@@ -65,6 +73,10 @@ export interface WorkLogEntry {
|
||||
toolTitle?: string;
|
||||
itemType?: ToolLifecycleItemType;
|
||||
requestKind?: PendingApproval["requestKind"];
|
||||
/** From runtime item / task payload `status` when present (e.g. tool.updated). */
|
||||
toolLifecycleStatus?: WorkLogToolLifecycleStatus;
|
||||
/** Originating orchestration activity kind (e.g. `user-input.requested`) for row chrome. */
|
||||
sourceActivityKind?: OrchestrationThreadActivity["kind"];
|
||||
}
|
||||
|
||||
interface DerivedWorkLogEntry extends WorkLogEntry {
|
||||
@@ -126,10 +138,137 @@ export type TimelineEntry =
|
||||
entry: WorkLogEntry;
|
||||
};
|
||||
|
||||
export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
|
||||
if (entry.tone === "tool" || entry.tone === "thinking" || entry.tone === "error") {
|
||||
return true;
|
||||
}
|
||||
if (entry.command !== undefined && entry.command.trim().length > 0) {
|
||||
return true;
|
||||
}
|
||||
if (entry.requestKind !== undefined) {
|
||||
return true;
|
||||
}
|
||||
return entry.itemType !== undefined && isToolLifecycleItemType(entry.itemType);
|
||||
}
|
||||
|
||||
/** Heuristic: providers often emit successful lifecycle status while error text lives in `detail` / `command`. */
|
||||
function toolDetailTextLooksLikeFailure(text: string): boolean {
|
||||
const t = text.toLowerCase();
|
||||
if (t.includes("file not found")) {
|
||||
return true;
|
||||
}
|
||||
if (t.includes("no files found")) {
|
||||
return true;
|
||||
}
|
||||
if (
|
||||
t.includes("enoent") ||
|
||||
t.includes("no such file or directory") ||
|
||||
t.includes("no such file")
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
if (t.includes("cannot find path") && t.includes("because it does not exist")) {
|
||||
return true;
|
||||
}
|
||||
if (t.includes("commandnotfoundexception")) {
|
||||
return true;
|
||||
}
|
||||
if (t.includes("is not recognized as the name of a cmdlet")) {
|
||||
return true;
|
||||
}
|
||||
if (t.includes("is not recognized") && t.includes("the term '")) {
|
||||
return true;
|
||||
}
|
||||
if (t.includes("a parameter cannot be found that matches parameter name")) {
|
||||
return true;
|
||||
}
|
||||
if (t.includes("command not found")) {
|
||||
return true;
|
||||
}
|
||||
if (/<exited with exit code\s+[1-9]\d*\s*>/i.test(text)) {
|
||||
return true;
|
||||
}
|
||||
if (/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text)) {
|
||||
return true;
|
||||
}
|
||||
if (/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** True when the row should show a failure affordance (explicit status/tone or error-shaped tool output). */
|
||||
export function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean {
|
||||
if (entry.tone === "error") {
|
||||
return true;
|
||||
}
|
||||
const ls = entry.toolLifecycleStatus;
|
||||
if (ls === "failed" || ls === "declined") {
|
||||
return true;
|
||||
}
|
||||
if (!workLogEntryIsToolLike(entry)) {
|
||||
return false;
|
||||
}
|
||||
const parts: string[] = [];
|
||||
if (entry.detail) {
|
||||
parts.push(entry.detail);
|
||||
}
|
||||
if (entry.command) {
|
||||
parts.push(entry.command);
|
||||
}
|
||||
const blob = parts.join("\n");
|
||||
if (blob.length === 0) {
|
||||
return false;
|
||||
}
|
||||
return toolDetailTextLooksLikeFailure(blob);
|
||||
}
|
||||
|
||||
/** Tool/command row completed without failure (blue check affordance). */
|
||||
export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {
|
||||
if (!workLogEntryIsToolLike(entry)) {
|
||||
return false;
|
||||
}
|
||||
if (workEntryIndicatesToolFailure(entry)) {
|
||||
return false;
|
||||
}
|
||||
if (entry.tone === "thinking") {
|
||||
return false;
|
||||
}
|
||||
const ls = entry.toolLifecycleStatus;
|
||||
if (ls === "failed" || ls === "declined") {
|
||||
return false;
|
||||
}
|
||||
if (ls === "inProgress") {
|
||||
return false;
|
||||
}
|
||||
if (ls === "stopped") {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Tool-like row with neither clear success nor failure (empty, incomplete, in progress, etc.). */
|
||||
export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean {
|
||||
if (!workLogEntryIsToolLike(entry)) {
|
||||
return false;
|
||||
}
|
||||
if (workEntryIndicatesToolFailure(entry)) {
|
||||
return false;
|
||||
}
|
||||
if (workEntryIndicatesToolSuccess(entry)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function formatDuration(durationMs: number): string {
|
||||
if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
|
||||
if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
|
||||
if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
|
||||
if (durationMs < 10_000) {
|
||||
const tenths = Math.round(durationMs / 100) / 10;
|
||||
// 9.95s+ rounds up to the next bucket — render "10s", not "10.0s".
|
||||
return tenths >= 10 ? "10s" : `${tenths.toFixed(1)}s`;
|
||||
}
|
||||
if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
|
||||
const minutes = Math.floor(durationMs / 60_000);
|
||||
const seconds = Math.round((durationMs % 60_000) / 1_000);
|
||||
@@ -207,7 +346,9 @@ function isStalePendingRequestFailureDetail(detail: string | undefined): boolean
|
||||
normalized.includes("stale pending user-input request") ||
|
||||
normalized.includes("unknown pending approval request") ||
|
||||
normalized.includes("unknown pending permission request") ||
|
||||
normalized.includes("unknown pending user-input request")
|
||||
normalized.includes("unknown pending user-input request") ||
|
||||
normalized.includes("unknown pending user input request") ||
|
||||
normalized.includes("unknown pending codex user input request")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -485,12 +626,10 @@ export function hasActionableProposedPlan(
|
||||
|
||||
export function deriveWorkLogEntries(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
latestTurnId: TurnId | undefined,
|
||||
): WorkLogEntry[] {
|
||||
const ordered = [...activities].toSorted(compareActivitiesByOrder);
|
||||
const entries: DerivedWorkLogEntry[] = [];
|
||||
for (const activity of ordered) {
|
||||
if (latestTurnId && activity.turnId !== latestTurnId) continue;
|
||||
if (activity.kind === "tool.started") continue;
|
||||
if (activity.kind === "task.started") continue;
|
||||
if (activity.kind === "context-window.updated") continue;
|
||||
@@ -498,9 +637,10 @@ export function deriveWorkLogEntries(
|
||||
if (isPlanBoundaryToolActivity(activity)) continue;
|
||||
entries.push(toDerivedWorkLogEntry(activity));
|
||||
}
|
||||
return collapseDerivedWorkLogEntries(entries).map(
|
||||
({ activityKind: _activityKind, collapseKey: _collapseKey, ...entry }) => entry,
|
||||
);
|
||||
return collapseDerivedWorkLogEntries(entries).map((entry) => {
|
||||
const { activityKind, collapseKey: _collapseKey, ...rest } = entry;
|
||||
return Object.assign(rest, { sourceActivityKind: activityKind });
|
||||
});
|
||||
}
|
||||
|
||||
function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): boolean {
|
||||
@@ -515,6 +655,25 @@ function isPlanBoundaryToolActivity(activity: OrchestrationThreadActivity): bool
|
||||
return typeof payload?.detail === "string" && payload.detail.startsWith("ExitPlanMode:");
|
||||
}
|
||||
|
||||
function extractWorkLogToolLifecycleStatus(
|
||||
payload: Record<string, unknown> | null,
|
||||
): WorkLogToolLifecycleStatus | undefined {
|
||||
if (!payload) {
|
||||
return undefined;
|
||||
}
|
||||
const s = payload.status;
|
||||
if (
|
||||
s === "inProgress" ||
|
||||
s === "completed" ||
|
||||
s === "failed" ||
|
||||
s === "declined" ||
|
||||
s === "stopped"
|
||||
) {
|
||||
return s;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWorkLogEntry {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
@@ -548,6 +707,7 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
const entry: DerivedWorkLogEntry = {
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
turnId: activity.turnId,
|
||||
label: taskLabel || activity.summary,
|
||||
tone:
|
||||
activity.kind === "task.progress"
|
||||
@@ -583,6 +743,13 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
if (toolCallId) {
|
||||
entry.toolCallId = toolCallId;
|
||||
}
|
||||
let toolLifecycleStatus = extractWorkLogToolLifecycleStatus(payload);
|
||||
if (!toolLifecycleStatus && activity.kind === "tool.completed") {
|
||||
toolLifecycleStatus = "completed";
|
||||
}
|
||||
if (toolLifecycleStatus) {
|
||||
entry.toolLifecycleStatus = toolLifecycleStatus;
|
||||
}
|
||||
const collapseKey = deriveToolLifecycleCollapseKey(entry);
|
||||
if (collapseKey) {
|
||||
entry.collapseKey = collapseKey;
|
||||
@@ -643,6 +810,7 @@ function mergeDerivedWorkLogEntries(
|
||||
const requestKind = next.requestKind ?? previous.requestKind;
|
||||
const collapseKey = next.collapseKey ?? previous.collapseKey;
|
||||
const toolCallId = next.toolCallId ?? previous.toolCallId;
|
||||
const toolLifecycleStatus = next.toolLifecycleStatus ?? previous.toolLifecycleStatus;
|
||||
return {
|
||||
...previous,
|
||||
...next,
|
||||
@@ -655,6 +823,7 @@ function mergeDerivedWorkLogEntries(
|
||||
...(requestKind ? { requestKind } : {}),
|
||||
...(collapseKey ? { collapseKey } : {}),
|
||||
...(toolCallId ? { toolCallId } : {}),
|
||||
...(toolLifecycleStatus !== undefined ? { toolLifecycleStatus } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1160,14 +1329,6 @@ function compareActivityLifecycleRank(kind: string): number {
|
||||
return 1;
|
||||
}
|
||||
|
||||
export function hasToolActivityForTurn(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
turnId: TurnId | null | undefined,
|
||||
): boolean {
|
||||
if (!turnId) return false;
|
||||
return activities.some((activity) => activity.turnId === turnId && activity.tone === "tool");
|
||||
}
|
||||
|
||||
export function deriveTimelineEntries(
|
||||
messages: ChatMessage[],
|
||||
proposedPlans: ProposedPlan[],
|
||||
@@ -1196,53 +1357,6 @@ export function deriveTimelineEntries(
|
||||
);
|
||||
}
|
||||
|
||||
export function deriveCompletionDividerBeforeEntryId(
|
||||
timelineEntries: ReadonlyArray<TimelineEntry>,
|
||||
latestTurn: Pick<
|
||||
OrchestrationLatestTurn,
|
||||
"assistantMessageId" | "startedAt" | "completedAt"
|
||||
> | null,
|
||||
): string | null {
|
||||
if (!latestTurn?.startedAt || !latestTurn.completedAt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (latestTurn.assistantMessageId) {
|
||||
const exactMatch = timelineEntries.find(
|
||||
(timelineEntry) =>
|
||||
timelineEntry.kind === "message" &&
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
timelineEntry.message.id === latestTurn.assistantMessageId,
|
||||
);
|
||||
if (exactMatch) {
|
||||
return exactMatch.id;
|
||||
}
|
||||
}
|
||||
|
||||
const turnStartedAt = Date.parse(latestTurn.startedAt);
|
||||
const turnCompletedAt = Date.parse(latestTurn.completedAt);
|
||||
if (Number.isNaN(turnStartedAt) || Number.isNaN(turnCompletedAt)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let inRangeMatch: string | null = null;
|
||||
let fallbackMatch: string | null = null;
|
||||
for (const timelineEntry of timelineEntries) {
|
||||
if (timelineEntry.kind !== "message" || timelineEntry.message.role !== "assistant") {
|
||||
continue;
|
||||
}
|
||||
const messageAt = Date.parse(timelineEntry.message.createdAt);
|
||||
if (Number.isNaN(messageAt) || messageAt < turnStartedAt) {
|
||||
continue;
|
||||
}
|
||||
fallbackMatch = timelineEntry.id;
|
||||
if (messageAt <= turnCompletedAt) {
|
||||
inRangeMatch = timelineEntry.id;
|
||||
}
|
||||
}
|
||||
return inRangeMatch ?? fallbackMatch;
|
||||
}
|
||||
|
||||
export function inferCheckpointTurnCountByTurnId(
|
||||
summaries: TurnDiffSummary[],
|
||||
): Record<TurnId, number> {
|
||||
|
||||
@@ -776,9 +776,40 @@ describe("incremental orchestration updates", () => {
|
||||
localEnvironmentId,
|
||||
);
|
||||
|
||||
// A completed assistant message must not settle the turn while the
|
||||
// session is still running it — providers emit interim assistant
|
||||
// messages between tool calls.
|
||||
expect(threadsOf(next)[0]?.session?.status).toBe("running");
|
||||
expect(threadsOf(next)[0]?.latestTurn?.state).toBe("completed");
|
||||
expect(threadsOf(next)[0]?.latestTurn?.state).toBe("running");
|
||||
expect(threadsOf(next)[0]?.latestTurn?.completedAt).toBeNull();
|
||||
expect(threadsOf(next)[0]?.messages).toHaveLength(1);
|
||||
|
||||
const settled = applyOrchestrationEvents(
|
||||
next,
|
||||
[
|
||||
makeEvent(
|
||||
"thread.session-set",
|
||||
{
|
||||
threadId: thread.id,
|
||||
session: {
|
||||
threadId: thread.id,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-27T00:00:04.000Z",
|
||||
},
|
||||
},
|
||||
{ sequence: 4 },
|
||||
),
|
||||
],
|
||||
localEnvironmentId,
|
||||
);
|
||||
|
||||
// Leaving the running session status is the turn-end signal.
|
||||
expect(threadsOf(settled)[0]?.latestTurn?.state).toBe("completed");
|
||||
expect(threadsOf(settled)[0]?.latestTurn?.completedAt).toBe("2026-02-27T00:00:04.000Z");
|
||||
});
|
||||
|
||||
it("does not regress latestTurn when an older turn diff completes late", () => {
|
||||
|
||||
+77
-17
@@ -885,6 +885,29 @@ function buildLatestTurn(params: {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn state to settle a still-running latest turn with when its session
|
||||
* leaves the "running" status, or null while the session is (re)starting or
|
||||
* running and the turn must stay unsettled.
|
||||
*/
|
||||
function settledTurnStateForSessionStatus(
|
||||
status: OrchestrationSessionStatus,
|
||||
): "completed" | "interrupted" | "error" | null {
|
||||
switch (status) {
|
||||
case "idle":
|
||||
case "ready":
|
||||
return "completed";
|
||||
case "error":
|
||||
return "error";
|
||||
case "interrupted":
|
||||
case "stopped":
|
||||
return "interrupted";
|
||||
case "starting":
|
||||
case "running":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function rebindTurnDiffSummariesForAssistantMessage(
|
||||
turnDiffSummaries: ReadonlyArray<TurnDiffSummary>,
|
||||
turnId: TurnId,
|
||||
@@ -1419,6 +1442,15 @@ function applyEnvironmentOrchestrationEvent(
|
||||
event.payload.messageId,
|
||||
)
|
||||
: thread.turnDiffSummaries;
|
||||
// A completed assistant message only settles the turn once the
|
||||
// session is no longer running it — providers may emit several
|
||||
// assistant messages per turn (commentary between tool calls), and
|
||||
// the turn must stay unsettled until the provider reports turn end.
|
||||
const turnStillRunning =
|
||||
event.payload.turnId !== null &&
|
||||
thread.session?.orchestrationStatus === "running" &&
|
||||
thread.session.activeTurnId === event.payload.turnId;
|
||||
const settlesTurn = !event.payload.streaming && !turnStillRunning;
|
||||
const latestTurn: Thread["latestTurn"] =
|
||||
event.payload.role === "assistant" &&
|
||||
event.payload.turnId !== null &&
|
||||
@@ -1426,13 +1458,13 @@ function applyEnvironmentOrchestrationEvent(
|
||||
? buildLatestTurn({
|
||||
previous: thread.latestTurn,
|
||||
turnId: event.payload.turnId,
|
||||
state: event.payload.streaming
|
||||
? "running"
|
||||
: thread.latestTurn?.state === "interrupted"
|
||||
state: settlesTurn
|
||||
? thread.latestTurn?.state === "interrupted"
|
||||
? "interrupted"
|
||||
: thread.latestTurn?.state === "error"
|
||||
? "error"
|
||||
: "completed",
|
||||
: "completed"
|
||||
: "running",
|
||||
requestedAt:
|
||||
thread.latestTurn?.turnId === event.payload.turnId
|
||||
? thread.latestTurn.requestedAt
|
||||
@@ -1442,11 +1474,11 @@ function applyEnvironmentOrchestrationEvent(
|
||||
? (thread.latestTurn.startedAt ?? event.payload.createdAt)
|
||||
: event.payload.createdAt,
|
||||
sourceProposedPlan: thread.pendingSourceProposedPlan,
|
||||
completedAt: event.payload.streaming
|
||||
? thread.latestTurn?.turnId === event.payload.turnId
|
||||
completedAt: settlesTurn
|
||||
? event.payload.updatedAt
|
||||
: thread.latestTurn?.turnId === event.payload.turnId
|
||||
? (thread.latestTurn.completedAt ?? null)
|
||||
: null
|
||||
: event.payload.updatedAt,
|
||||
: null,
|
||||
assistantMessageId: event.payload.messageId,
|
||||
})
|
||||
: thread.latestTurn;
|
||||
@@ -1460,11 +1492,12 @@ function applyEnvironmentOrchestrationEvent(
|
||||
});
|
||||
|
||||
case "thread.session-set":
|
||||
return updateThreadState(state, event.payload.threadId, (thread) => ({
|
||||
...thread,
|
||||
session: mapSession(event.payload.session),
|
||||
error: sanitizeThreadErrorMessage(event.payload.session.lastError),
|
||||
latestTurn:
|
||||
return updateThreadState(state, event.payload.threadId, (thread) => {
|
||||
// Leaving the "running" session status is the turn-end signal:
|
||||
// settle a still-running latest turn so its duration reflects the
|
||||
// whole turn, not the last assistant message.
|
||||
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
|
||||
const latestTurn: Thread["latestTurn"] =
|
||||
event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
|
||||
? buildLatestTurn({
|
||||
previous: thread.latestTurn,
|
||||
@@ -1485,9 +1518,30 @@ function applyEnvironmentOrchestrationEvent(
|
||||
: null,
|
||||
sourceProposedPlan: thread.pendingSourceProposedPlan,
|
||||
})
|
||||
: thread.latestTurn,
|
||||
updatedAt: event.occurredAt,
|
||||
}));
|
||||
: thread.latestTurn !== null &&
|
||||
thread.latestTurn.state === "running" &&
|
||||
settledTurnState !== null
|
||||
? buildLatestTurn({
|
||||
previous: thread.latestTurn,
|
||||
turnId: thread.latestTurn.turnId,
|
||||
state: settledTurnState,
|
||||
requestedAt: thread.latestTurn.requestedAt,
|
||||
startedAt: thread.latestTurn.startedAt,
|
||||
// A running turn's completedAt can only hold a mid-turn
|
||||
// placeholder checkpoint timestamp — the session leaving
|
||||
// "running" is the authoritative turn end.
|
||||
completedAt: event.payload.session.updatedAt,
|
||||
assistantMessageId: thread.latestTurn.assistantMessageId,
|
||||
})
|
||||
: thread.latestTurn;
|
||||
return {
|
||||
...thread,
|
||||
session: mapSession(event.payload.session),
|
||||
error: sanitizeThreadErrorMessage(event.payload.session.lastError),
|
||||
latestTurn,
|
||||
updatedAt: event.occurredAt,
|
||||
};
|
||||
});
|
||||
|
||||
case "thread.session-stop-requested":
|
||||
return updateThreadState(state, event.payload.threadId, (thread) =>
|
||||
@@ -1552,8 +1606,14 @@ function applyEnvironmentOrchestrationEvent(
|
||||
(right.checkpointTurnCount ?? Number.MAX_SAFE_INTEGER),
|
||||
)
|
||||
.slice(-MAX_THREAD_CHECKPOINTS);
|
||||
// Mid-turn diff updates produce placeholder checkpoints; record the
|
||||
// diff summary, but don't settle a turn its session is still running.
|
||||
const turnStillRunning =
|
||||
thread.session?.orchestrationStatus === "running" &&
|
||||
thread.session.activeTurnId === event.payload.turnId;
|
||||
const latestTurn =
|
||||
thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId
|
||||
!turnStillRunning &&
|
||||
(thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
|
||||
? buildLatestTurn({
|
||||
previous: thread.latestTurn,
|
||||
turnId: event.payload.turnId,
|
||||
|
||||
@@ -44,6 +44,40 @@ export function formatTimestamp(isoDate: string, timestampFormat: TimestampForma
|
||||
return getTimestampFormatter(timestampFormat, true).format(new Date(isoDate));
|
||||
}
|
||||
|
||||
const monthNameFormatter = new Intl.DateTimeFormat(undefined, { month: "long" });
|
||||
|
||||
function ordinalSuffix(day: number): string {
|
||||
const lastTwo = day % 100;
|
||||
if (lastTwo >= 11 && lastTwo <= 13) return "th";
|
||||
switch (day % 10) {
|
||||
case 1:
|
||||
return "st";
|
||||
case 2:
|
||||
return "nd";
|
||||
case 3:
|
||||
return "rd";
|
||||
default:
|
||||
return "th";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Long-form tooltip label, e.g. `12:04, 4th June`.
|
||||
* Renders the wall-clock time without seconds followed by the ordinal day and month name.
|
||||
*/
|
||||
export function formatChatTimestampTooltip(
|
||||
isoDate: string,
|
||||
timestampFormat: TimestampFormat,
|
||||
): string {
|
||||
const date = new Date(isoDate);
|
||||
if (Number.isNaN(date.getTime())) return "";
|
||||
const time = formatShortTimestamp(isoDate, timestampFormat);
|
||||
const day = date.getDate();
|
||||
const month = monthNameFormatter.format(date);
|
||||
const year = date.getFullYear();
|
||||
return `${time}, ${day}${ordinalSuffix(day)} ${month} ${year}`;
|
||||
}
|
||||
|
||||
export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
|
||||
return getTimestampFormatter(timestampFormat, false).format(new Date(isoDate));
|
||||
}
|
||||
|
||||
@@ -288,9 +288,98 @@ describe("applyThreadDetailEvent", () => {
|
||||
expect(result.thread.latestTurn?.assistantMessageId).toBe("msg-3");
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps latestTurn running for interim assistant messages while the session runs the turn", () => {
|
||||
const threadWithRunningSession: OrchestrationThread = {
|
||||
...baseThread,
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "running",
|
||||
providerName: "claude",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: TurnId.make("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-04-01T06:59:00.000Z",
|
||||
},
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T06:59:00.000Z",
|
||||
startedAt: "2026-04-01T06:59:00.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: null,
|
||||
},
|
||||
};
|
||||
|
||||
const result = applyThreadDetailEvent(threadWithRunningSession, {
|
||||
...baseEventFields,
|
||||
sequence: 8,
|
||||
occurredAt: "2026-04-01T07:00:00.000Z",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
type: "thread.message-sent",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
messageId: MessageId.make("msg-3"),
|
||||
role: "assistant",
|
||||
text: "Interim commentary between tool calls.",
|
||||
turnId: TurnId.make("turn-1"),
|
||||
streaming: false,
|
||||
createdAt: "2026-04-01T07:00:00.000Z",
|
||||
updatedAt: "2026-04-01T07:00:00.000Z",
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.kind).toBe("updated");
|
||||
if (result.kind === "updated") {
|
||||
expect(result.thread.latestTurn?.state).toBe("running");
|
||||
expect(result.thread.latestTurn?.completedAt).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("thread.session-set", () => {
|
||||
it("settles a running latestTurn when the session leaves the running status", () => {
|
||||
const threadWithRunningTurn: OrchestrationThread = {
|
||||
...baseThread,
|
||||
latestTurn: {
|
||||
turnId: TurnId.make("turn-1"),
|
||||
state: "running",
|
||||
requestedAt: "2026-04-01T07:00:00.000Z",
|
||||
startedAt: "2026-04-01T07:00:00.000Z",
|
||||
completedAt: null,
|
||||
assistantMessageId: MessageId.make("msg-3"),
|
||||
},
|
||||
};
|
||||
|
||||
const result = applyThreadDetailEvent(threadWithRunningTurn, {
|
||||
...baseEventFields,
|
||||
sequence: 9,
|
||||
occurredAt: "2026-04-01T08:00:00.000Z",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.make("thread-1"),
|
||||
type: "thread.session-set",
|
||||
payload: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claude",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: "2026-04-01T08:00:00.000Z",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(result.kind).toBe("updated");
|
||||
if (result.kind === "updated") {
|
||||
expect(result.thread.latestTurn?.state).toBe("completed");
|
||||
expect(result.thread.latestTurn?.completedAt).toBe("2026-04-01T08:00:00.000Z");
|
||||
}
|
||||
});
|
||||
|
||||
it("updates session and latestTurn for a running session", () => {
|
||||
const result = applyThreadDetailEvent(baseThread, {
|
||||
...baseEventFields,
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
OrchestrationEvent,
|
||||
OrchestrationLatestTurn,
|
||||
OrchestrationMessage,
|
||||
OrchestrationSession,
|
||||
OrchestrationThread,
|
||||
OrchestrationThreadActivity,
|
||||
TurnId,
|
||||
@@ -232,20 +233,29 @@ export function applyThreadDetailEvent(
|
||||
: Arr.append(thread.messages, message);
|
||||
const cappedMessages = Arr.takeRight(messages, limits.maxMessages);
|
||||
|
||||
// Update latestTurn for assistant messages bound to a turn.
|
||||
// Update latestTurn for assistant messages bound to a turn. A completed
|
||||
// assistant message only settles the turn once the session is no longer
|
||||
// running it — providers may emit several assistant messages per turn
|
||||
// (commentary between tool calls), and the turn must stay unsettled
|
||||
// until the provider reports turn end.
|
||||
const turnStillRunning =
|
||||
event.payload.turnId !== null &&
|
||||
thread.session?.status === "running" &&
|
||||
thread.session.activeTurnId === event.payload.turnId;
|
||||
const settlesTurn = !event.payload.streaming && !turnStillRunning;
|
||||
const latestTurn: OrchestrationThread["latestTurn"] =
|
||||
event.payload.role === "assistant" &&
|
||||
event.payload.turnId !== null &&
|
||||
(thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
|
||||
? {
|
||||
turnId: event.payload.turnId,
|
||||
state: event.payload.streaming
|
||||
? "running"
|
||||
: thread.latestTurn?.state === "interrupted"
|
||||
state: settlesTurn
|
||||
? thread.latestTurn?.state === "interrupted"
|
||||
? "interrupted"
|
||||
: thread.latestTurn?.state === "error"
|
||||
? "error"
|
||||
: "completed",
|
||||
: "completed"
|
||||
: "running",
|
||||
requestedAt:
|
||||
thread.latestTurn?.turnId === event.payload.turnId
|
||||
? thread.latestTurn.requestedAt
|
||||
@@ -254,11 +264,11 @@ export function applyThreadDetailEvent(
|
||||
thread.latestTurn?.turnId === event.payload.turnId
|
||||
? (thread.latestTurn.startedAt ?? event.payload.createdAt)
|
||||
: event.payload.createdAt,
|
||||
completedAt: event.payload.streaming
|
||||
? thread.latestTurn?.turnId === event.payload.turnId
|
||||
completedAt: settlesTurn
|
||||
? event.payload.updatedAt
|
||||
: thread.latestTurn?.turnId === event.payload.turnId
|
||||
? (thread.latestTurn.completedAt ?? null)
|
||||
: null
|
||||
: event.payload.updatedAt,
|
||||
: null,
|
||||
assistantMessageId: event.payload.messageId,
|
||||
}
|
||||
: thread.latestTurn;
|
||||
@@ -287,6 +297,9 @@ export function applyThreadDetailEvent(
|
||||
|
||||
// ── Session ─────────────────────────────────────────────────────
|
||||
case "thread.session-set": {
|
||||
// Leaving the "running" session status is the turn-end signal: settle a
|
||||
// still-running latest turn so its duration reflects the whole turn.
|
||||
const settledTurnState = settledTurnStateForSessionStatus(event.payload.session.status);
|
||||
const latestTurn: OrchestrationLatestTurn | null =
|
||||
event.payload.session.status === "running" && event.payload.session.activeTurnId !== null
|
||||
? {
|
||||
@@ -306,7 +319,18 @@ export function applyThreadDetailEvent(
|
||||
? thread.latestTurn.assistantMessageId
|
||||
: null,
|
||||
}
|
||||
: thread.latestTurn;
|
||||
: thread.latestTurn !== null &&
|
||||
thread.latestTurn.state === "running" &&
|
||||
settledTurnState !== null
|
||||
? {
|
||||
...thread.latestTurn,
|
||||
state: settledTurnState,
|
||||
// A running turn's completedAt can only hold a mid-turn
|
||||
// placeholder checkpoint timestamp — the session leaving
|
||||
// "running" is the authoritative turn end.
|
||||
completedAt: event.payload.session.updatedAt,
|
||||
}
|
||||
: thread.latestTurn;
|
||||
|
||||
return {
|
||||
kind: "updated",
|
||||
@@ -380,8 +404,14 @@ export function applyThreadDetailEvent(
|
||||
Arr.takeRight(limits.maxCheckpoints),
|
||||
);
|
||||
|
||||
// Mid-turn diff updates produce placeholder checkpoints; record the
|
||||
// checkpoint, but don't settle a turn its session is still running.
|
||||
const diffTurnStillRunning =
|
||||
thread.session?.status === "running" &&
|
||||
thread.session.activeTurnId === event.payload.turnId;
|
||||
const latestTurn =
|
||||
thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId
|
||||
!diffTurnStillRunning &&
|
||||
(thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
|
||||
? {
|
||||
turnId: event.payload.turnId,
|
||||
state: checkpointStatusToTurnState(event.payload.status),
|
||||
@@ -482,6 +512,29 @@ export function applyThreadDetailEvent(
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Turn state to settle a still-running latest turn with when its session
|
||||
* leaves the "running" status, or null while the session is (re)starting or
|
||||
* running and the turn must stay unsettled.
|
||||
*/
|
||||
function settledTurnStateForSessionStatus(
|
||||
status: OrchestrationSession["status"],
|
||||
): "completed" | "interrupted" | "error" | null {
|
||||
switch (status) {
|
||||
case "idle":
|
||||
case "ready":
|
||||
return "completed";
|
||||
case "error":
|
||||
return "error";
|
||||
case "interrupted":
|
||||
case "stopped":
|
||||
return "interrupted";
|
||||
case "starting":
|
||||
case "running":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function checkpointStatusToTurnState(
|
||||
status: "ready" | "missing" | "error",
|
||||
): OrchestrationLatestTurn["state"] {
|
||||
|
||||
@@ -17,7 +17,7 @@ import {
|
||||
} from "effect/unstable/http";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
const UPSTREAM_REF = "07b695190f30a450e4921f71f77473e564395c59";
|
||||
const UPSTREAM_REF = "b39f943a634a6e7ba86c3d6e8cf6d5f35e612566";
|
||||
const USER_AGENT = "effect-codex-app-server-generator";
|
||||
const GITHUB_API_BASE =
|
||||
"https://api.github.com/repos/openai/codex/contents/codex-rs/app-server-protocol";
|
||||
@@ -348,6 +348,7 @@ function resolveResponseTypeName(
|
||||
const overrides: Record<string, string> = {
|
||||
"account/logout": "LogoutAccountResponse",
|
||||
"account/rateLimits/read": "GetAccountRateLimitsResponse",
|
||||
"account/usage/read": "GetAccountTokenUsageResponse",
|
||||
"config/batchWrite": "ConfigWriteResponse",
|
||||
"config/mcpServer/reload": "McpServerRefreshResponse",
|
||||
"config/value/write": "ConfigWriteResponse",
|
||||
@@ -745,14 +746,16 @@ const generateFiles = Effect.fn("generateFiles")(function* () {
|
||||
yield* Effect.log(`Generated Codex App Server schemas from ${UPSTREAM_REF}`);
|
||||
|
||||
yield* Effect.service(ChildProcessSpawner.ChildProcessSpawner).pipe(
|
||||
Effect.flatMap((spawner) => spawner.spawn(ChildProcess.make("bun", ["oxfmt", generatedDir]))),
|
||||
Effect.flatMap((spawner) =>
|
||||
spawner.spawn(ChildProcess.make("vp", ["fmt", generatedDir, "--write"])),
|
||||
),
|
||||
Effect.flatMap((child) => child.exitCode),
|
||||
Effect.tap((code) =>
|
||||
code === 0
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new GeneratorError({
|
||||
detail: `oxfmt failed with exit code ${code}`,
|
||||
detail: `vp fmt failed with exit code ${code}`,
|
||||
}),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// This file is generated by the effect-codex-app-server package. Do not edit manually.
|
||||
// Upstream protocol ref: 07b695190f30a450e4921f71f77473e564395c59
|
||||
// Upstream protocol ref: b39f943a634a6e7ba86c3d6e8cf6d5f35e612566
|
||||
|
||||
import * as CodexSchema from "./schema.gen.ts";
|
||||
|
||||
@@ -9,8 +9,12 @@ export const CLIENT_REQUEST_METHODS = {
|
||||
"thread/resume": "thread/resume",
|
||||
"thread/fork": "thread/fork",
|
||||
"thread/archive": "thread/archive",
|
||||
"thread/delete": "thread/delete",
|
||||
"thread/unsubscribe": "thread/unsubscribe",
|
||||
"thread/name/set": "thread/name/set",
|
||||
"thread/goal/set": "thread/goal/set",
|
||||
"thread/goal/get": "thread/goal/get",
|
||||
"thread/goal/clear": "thread/goal/clear",
|
||||
"thread/metadata/update": "thread/metadata/update",
|
||||
"thread/unarchive": "thread/unarchive",
|
||||
"thread/compact/start": "thread/compact/start",
|
||||
@@ -22,16 +26,19 @@ export const CLIENT_REQUEST_METHODS = {
|
||||
"thread/read": "thread/read",
|
||||
"thread/inject_items": "thread/inject_items",
|
||||
"skills/list": "skills/list",
|
||||
"skills/extraRoots/set": "skills/extraRoots/set",
|
||||
"hooks/list": "hooks/list",
|
||||
"marketplace/add": "marketplace/add",
|
||||
"marketplace/remove": "marketplace/remove",
|
||||
"marketplace/upgrade": "marketplace/upgrade",
|
||||
"plugin/list": "plugin/list",
|
||||
"plugin/installed": "plugin/installed",
|
||||
"plugin/read": "plugin/read",
|
||||
"plugin/skill/read": "plugin/skill/read",
|
||||
"plugin/share/save": "plugin/share/save",
|
||||
"plugin/share/updateTargets": "plugin/share/updateTargets",
|
||||
"plugin/share/list": "plugin/share/list",
|
||||
"plugin/share/checkout": "plugin/share/checkout",
|
||||
"plugin/share/delete": "plugin/share/delete",
|
||||
"app/list": "app/list",
|
||||
"fs/readFile": "fs/readFile",
|
||||
@@ -53,6 +60,7 @@ export const CLIENT_REQUEST_METHODS = {
|
||||
"model/list": "model/list",
|
||||
"modelProvider/capabilities/read": "modelProvider/capabilities/read",
|
||||
"experimentalFeature/list": "experimentalFeature/list",
|
||||
"permissionProfile/list": "permissionProfile/list",
|
||||
"experimentalFeature/enablement/set": "experimentalFeature/enablement/set",
|
||||
"mcpServer/oauth/login": "mcpServer/oauth/login",
|
||||
"config/mcpServer/reload": "config/mcpServer/reload",
|
||||
@@ -65,6 +73,7 @@ export const CLIENT_REQUEST_METHODS = {
|
||||
"account/login/cancel": "account/login/cancel",
|
||||
"account/logout": "account/logout",
|
||||
"account/rateLimits/read": "account/rateLimits/read",
|
||||
"account/usage/read": "account/usage/read",
|
||||
"account/sendAddCreditsNudgeEmail": "account/sendAddCreditsNudgeEmail",
|
||||
"feedback/upload": "feedback/upload",
|
||||
"command/exec": "command/exec",
|
||||
@@ -96,6 +105,7 @@ export const SERVER_REQUEST_METHODS = {
|
||||
"item/permissions/requestApproval": "item/permissions/requestApproval",
|
||||
"item/tool/call": "item/tool/call",
|
||||
"account/chatgptAuthTokens/refresh": "account/chatgptAuthTokens/refresh",
|
||||
"attestation/generate": "attestation/generate",
|
||||
applyPatchApproval: "applyPatchApproval",
|
||||
execCommandApproval: "execCommandApproval",
|
||||
} as const;
|
||||
@@ -105,12 +115,14 @@ export const SERVER_NOTIFICATION_METHODS = {
|
||||
"thread/started": "thread/started",
|
||||
"thread/status/changed": "thread/status/changed",
|
||||
"thread/archived": "thread/archived",
|
||||
"thread/deleted": "thread/deleted",
|
||||
"thread/unarchived": "thread/unarchived",
|
||||
"thread/closed": "thread/closed",
|
||||
"skills/changed": "skills/changed",
|
||||
"thread/name/updated": "thread/name/updated",
|
||||
"thread/goal/updated": "thread/goal/updated",
|
||||
"thread/goal/cleared": "thread/goal/cleared",
|
||||
"thread/settings/updated": "thread/settings/updated",
|
||||
"thread/tokenUsage/updated": "thread/tokenUsage/updated",
|
||||
"turn/started": "turn/started",
|
||||
"hook/started": "hook/started",
|
||||
@@ -148,6 +160,7 @@ export const SERVER_NOTIFICATION_METHODS = {
|
||||
"thread/compacted": "thread/compacted",
|
||||
"model/rerouted": "model/rerouted",
|
||||
"model/verification": "model/verification",
|
||||
"turn/moderationMetadata": "turn/moderationMetadata",
|
||||
warning: "warning",
|
||||
guardianWarning: "guardianWarning",
|
||||
deprecationNotice: "deprecationNotice",
|
||||
@@ -178,8 +191,12 @@ export interface ClientRequestParamsByMethod {
|
||||
readonly "thread/resume": CodexSchema.V2ThreadResumeParams;
|
||||
readonly "thread/fork": CodexSchema.V2ThreadForkParams;
|
||||
readonly "thread/archive": CodexSchema.V2ThreadArchiveParams;
|
||||
readonly "thread/delete": CodexSchema.V2ThreadDeleteParams;
|
||||
readonly "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams;
|
||||
readonly "thread/name/set": CodexSchema.V2ThreadSetNameParams;
|
||||
readonly "thread/goal/set": CodexSchema.V2ThreadGoalSetParams;
|
||||
readonly "thread/goal/get": CodexSchema.V2ThreadGoalGetParams;
|
||||
readonly "thread/goal/clear": CodexSchema.V2ThreadGoalClearParams;
|
||||
readonly "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams;
|
||||
readonly "thread/unarchive": CodexSchema.V2ThreadUnarchiveParams;
|
||||
readonly "thread/compact/start": CodexSchema.V2ThreadCompactStartParams;
|
||||
@@ -191,16 +208,19 @@ export interface ClientRequestParamsByMethod {
|
||||
readonly "thread/read": CodexSchema.V2ThreadReadParams;
|
||||
readonly "thread/inject_items": CodexSchema.V2ThreadInjectItemsParams;
|
||||
readonly "skills/list": CodexSchema.V2SkillsListParams;
|
||||
readonly "skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetParams;
|
||||
readonly "hooks/list": CodexSchema.V2HooksListParams;
|
||||
readonly "marketplace/add": CodexSchema.V2MarketplaceAddParams;
|
||||
readonly "marketplace/remove": CodexSchema.V2MarketplaceRemoveParams;
|
||||
readonly "marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeParams;
|
||||
readonly "plugin/list": CodexSchema.V2PluginListParams;
|
||||
readonly "plugin/installed": CodexSchema.V2PluginInstalledParams;
|
||||
readonly "plugin/read": CodexSchema.V2PluginReadParams;
|
||||
readonly "plugin/skill/read": CodexSchema.V2PluginSkillReadParams;
|
||||
readonly "plugin/share/save": CodexSchema.V2PluginShareSaveParams;
|
||||
readonly "plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsParams;
|
||||
readonly "plugin/share/list": CodexSchema.V2PluginShareListParams;
|
||||
readonly "plugin/share/checkout": CodexSchema.V2PluginShareCheckoutParams;
|
||||
readonly "plugin/share/delete": CodexSchema.V2PluginShareDeleteParams;
|
||||
readonly "app/list": CodexSchema.V2AppsListParams;
|
||||
readonly "fs/readFile": CodexSchema.V2FsReadFileParams;
|
||||
@@ -222,6 +242,7 @@ export interface ClientRequestParamsByMethod {
|
||||
readonly "model/list": CodexSchema.V2ModelListParams;
|
||||
readonly "modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadParams;
|
||||
readonly "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams;
|
||||
readonly "permissionProfile/list": CodexSchema.V2PermissionProfileListParams;
|
||||
readonly "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams;
|
||||
readonly "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams;
|
||||
readonly "config/mcpServer/reload": undefined;
|
||||
@@ -234,6 +255,7 @@ export interface ClientRequestParamsByMethod {
|
||||
readonly "account/login/cancel": CodexSchema.V2CancelLoginAccountParams;
|
||||
readonly "account/logout": undefined;
|
||||
readonly "account/rateLimits/read": undefined;
|
||||
readonly "account/usage/read": undefined;
|
||||
readonly "account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailParams;
|
||||
readonly "feedback/upload": CodexSchema.V2FeedbackUploadParams;
|
||||
readonly "command/exec": CodexSchema.V2CommandExecParams;
|
||||
@@ -259,8 +281,12 @@ export interface ClientRequestResponsesByMethod {
|
||||
readonly "thread/resume": CodexSchema.V2ThreadResumeResponse;
|
||||
readonly "thread/fork": CodexSchema.V2ThreadForkResponse;
|
||||
readonly "thread/archive": CodexSchema.V2ThreadArchiveResponse;
|
||||
readonly "thread/delete": CodexSchema.V2ThreadDeleteResponse;
|
||||
readonly "thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse;
|
||||
readonly "thread/name/set": CodexSchema.V2ThreadSetNameResponse;
|
||||
readonly "thread/goal/set": CodexSchema.V2ThreadGoalSetResponse;
|
||||
readonly "thread/goal/get": CodexSchema.V2ThreadGoalGetResponse;
|
||||
readonly "thread/goal/clear": CodexSchema.V2ThreadGoalClearResponse;
|
||||
readonly "thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse;
|
||||
readonly "thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse;
|
||||
readonly "thread/compact/start": CodexSchema.V2ThreadCompactStartResponse;
|
||||
@@ -272,16 +298,19 @@ export interface ClientRequestResponsesByMethod {
|
||||
readonly "thread/read": CodexSchema.V2ThreadReadResponse;
|
||||
readonly "thread/inject_items": CodexSchema.V2ThreadInjectItemsResponse;
|
||||
readonly "skills/list": CodexSchema.V2SkillsListResponse;
|
||||
readonly "skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetResponse;
|
||||
readonly "hooks/list": CodexSchema.V2HooksListResponse;
|
||||
readonly "marketplace/add": CodexSchema.V2MarketplaceAddResponse;
|
||||
readonly "marketplace/remove": CodexSchema.V2MarketplaceRemoveResponse;
|
||||
readonly "marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeResponse;
|
||||
readonly "plugin/list": CodexSchema.V2PluginListResponse;
|
||||
readonly "plugin/installed": CodexSchema.V2PluginInstalledResponse;
|
||||
readonly "plugin/read": CodexSchema.V2PluginReadResponse;
|
||||
readonly "plugin/skill/read": CodexSchema.V2PluginSkillReadResponse;
|
||||
readonly "plugin/share/save": CodexSchema.V2PluginShareSaveResponse;
|
||||
readonly "plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsResponse;
|
||||
readonly "plugin/share/list": CodexSchema.V2PluginShareListResponse;
|
||||
readonly "plugin/share/checkout": CodexSchema.V2PluginShareCheckoutResponse;
|
||||
readonly "plugin/share/delete": CodexSchema.V2PluginShareDeleteResponse;
|
||||
readonly "app/list": CodexSchema.V2AppsListResponse;
|
||||
readonly "fs/readFile": CodexSchema.V2FsReadFileResponse;
|
||||
@@ -303,6 +332,7 @@ export interface ClientRequestResponsesByMethod {
|
||||
readonly "model/list": CodexSchema.V2ModelListResponse;
|
||||
readonly "modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadResponse;
|
||||
readonly "experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse;
|
||||
readonly "permissionProfile/list": CodexSchema.V2PermissionProfileListResponse;
|
||||
readonly "experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse;
|
||||
readonly "mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse;
|
||||
readonly "config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse;
|
||||
@@ -315,6 +345,7 @@ export interface ClientRequestResponsesByMethod {
|
||||
readonly "account/login/cancel": CodexSchema.V2CancelLoginAccountResponse;
|
||||
readonly "account/logout": CodexSchema.V2LogoutAccountResponse;
|
||||
readonly "account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse;
|
||||
readonly "account/usage/read": CodexSchema.V2GetAccountTokenUsageResponse;
|
||||
readonly "account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailResponse;
|
||||
readonly "feedback/upload": CodexSchema.V2FeedbackUploadResponse;
|
||||
readonly "command/exec": CodexSchema.V2CommandExecResponse;
|
||||
@@ -346,6 +377,7 @@ export interface ServerRequestParamsByMethod {
|
||||
readonly "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams;
|
||||
readonly "item/tool/call": CodexSchema.DynamicToolCallParams;
|
||||
readonly "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams;
|
||||
readonly "attestation/generate": CodexSchema.AttestationGenerateParams;
|
||||
readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalParams;
|
||||
readonly execCommandApproval: CodexSchema.ExecCommandApprovalParams;
|
||||
}
|
||||
@@ -358,6 +390,7 @@ export interface ServerRequestResponsesByMethod {
|
||||
readonly "item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse;
|
||||
readonly "item/tool/call": CodexSchema.DynamicToolCallResponse;
|
||||
readonly "account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse;
|
||||
readonly "attestation/generate": CodexSchema.AttestationGenerateResponse;
|
||||
readonly applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse;
|
||||
readonly execCommandApproval: CodexSchema.ExecCommandApprovalResponse;
|
||||
}
|
||||
@@ -367,12 +400,14 @@ export interface ServerNotificationParamsByMethod {
|
||||
readonly "thread/started": CodexSchema.V2ThreadStartedNotification;
|
||||
readonly "thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification;
|
||||
readonly "thread/archived": CodexSchema.V2ThreadArchivedNotification;
|
||||
readonly "thread/deleted": CodexSchema.V2ThreadDeletedNotification;
|
||||
readonly "thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification;
|
||||
readonly "thread/closed": CodexSchema.V2ThreadClosedNotification;
|
||||
readonly "skills/changed": CodexSchema.V2SkillsChangedNotification;
|
||||
readonly "thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification;
|
||||
readonly "thread/goal/updated": CodexSchema.V2ThreadGoalUpdatedNotification;
|
||||
readonly "thread/goal/cleared": CodexSchema.V2ThreadGoalClearedNotification;
|
||||
readonly "thread/settings/updated": CodexSchema.V2ThreadSettingsUpdatedNotification;
|
||||
readonly "thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification;
|
||||
readonly "turn/started": CodexSchema.V2TurnStartedNotification;
|
||||
readonly "hook/started": CodexSchema.V2HookStartedNotification;
|
||||
@@ -410,6 +445,7 @@ export interface ServerNotificationParamsByMethod {
|
||||
readonly "thread/compacted": CodexSchema.V2ContextCompactedNotification;
|
||||
readonly "model/rerouted": CodexSchema.V2ModelReroutedNotification;
|
||||
readonly "model/verification": CodexSchema.V2ModelVerificationNotification;
|
||||
readonly "turn/moderationMetadata": CodexSchema.V2TurnModerationMetadataNotification;
|
||||
readonly warning: CodexSchema.V2WarningNotification;
|
||||
readonly guardianWarning: CodexSchema.V2GuardianWarningNotification;
|
||||
readonly deprecationNotice: CodexSchema.V2DeprecationNoticeNotification;
|
||||
@@ -435,8 +471,12 @@ export const CLIENT_REQUEST_PARAMS = {
|
||||
"thread/resume": CodexSchema.V2ThreadResumeParams,
|
||||
"thread/fork": CodexSchema.V2ThreadForkParams,
|
||||
"thread/archive": CodexSchema.V2ThreadArchiveParams,
|
||||
"thread/delete": CodexSchema.V2ThreadDeleteParams,
|
||||
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeParams,
|
||||
"thread/name/set": CodexSchema.V2ThreadSetNameParams,
|
||||
"thread/goal/set": CodexSchema.V2ThreadGoalSetParams,
|
||||
"thread/goal/get": CodexSchema.V2ThreadGoalGetParams,
|
||||
"thread/goal/clear": CodexSchema.V2ThreadGoalClearParams,
|
||||
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateParams,
|
||||
"thread/unarchive": CodexSchema.V2ThreadUnarchiveParams,
|
||||
"thread/compact/start": CodexSchema.V2ThreadCompactStartParams,
|
||||
@@ -448,16 +488,19 @@ export const CLIENT_REQUEST_PARAMS = {
|
||||
"thread/read": CodexSchema.V2ThreadReadParams,
|
||||
"thread/inject_items": CodexSchema.V2ThreadInjectItemsParams,
|
||||
"skills/list": CodexSchema.V2SkillsListParams,
|
||||
"skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetParams,
|
||||
"hooks/list": CodexSchema.V2HooksListParams,
|
||||
"marketplace/add": CodexSchema.V2MarketplaceAddParams,
|
||||
"marketplace/remove": CodexSchema.V2MarketplaceRemoveParams,
|
||||
"marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeParams,
|
||||
"plugin/list": CodexSchema.V2PluginListParams,
|
||||
"plugin/installed": CodexSchema.V2PluginInstalledParams,
|
||||
"plugin/read": CodexSchema.V2PluginReadParams,
|
||||
"plugin/skill/read": CodexSchema.V2PluginSkillReadParams,
|
||||
"plugin/share/save": CodexSchema.V2PluginShareSaveParams,
|
||||
"plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsParams,
|
||||
"plugin/share/list": CodexSchema.V2PluginShareListParams,
|
||||
"plugin/share/checkout": CodexSchema.V2PluginShareCheckoutParams,
|
||||
"plugin/share/delete": CodexSchema.V2PluginShareDeleteParams,
|
||||
"app/list": CodexSchema.V2AppsListParams,
|
||||
"fs/readFile": CodexSchema.V2FsReadFileParams,
|
||||
@@ -479,6 +522,7 @@ export const CLIENT_REQUEST_PARAMS = {
|
||||
"model/list": CodexSchema.V2ModelListParams,
|
||||
"modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadParams,
|
||||
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListParams,
|
||||
"permissionProfile/list": CodexSchema.V2PermissionProfileListParams,
|
||||
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetParams,
|
||||
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginParams,
|
||||
"config/mcpServer/reload": undefined,
|
||||
@@ -491,6 +535,7 @@ export const CLIENT_REQUEST_PARAMS = {
|
||||
"account/login/cancel": CodexSchema.V2CancelLoginAccountParams,
|
||||
"account/logout": undefined,
|
||||
"account/rateLimits/read": undefined,
|
||||
"account/usage/read": undefined,
|
||||
"account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailParams,
|
||||
"feedback/upload": CodexSchema.V2FeedbackUploadParams,
|
||||
"command/exec": CodexSchema.V2CommandExecParams,
|
||||
@@ -516,8 +561,12 @@ export const CLIENT_REQUEST_RESPONSES = {
|
||||
"thread/resume": CodexSchema.V2ThreadResumeResponse,
|
||||
"thread/fork": CodexSchema.V2ThreadForkResponse,
|
||||
"thread/archive": CodexSchema.V2ThreadArchiveResponse,
|
||||
"thread/delete": CodexSchema.V2ThreadDeleteResponse,
|
||||
"thread/unsubscribe": CodexSchema.V2ThreadUnsubscribeResponse,
|
||||
"thread/name/set": CodexSchema.V2ThreadSetNameResponse,
|
||||
"thread/goal/set": CodexSchema.V2ThreadGoalSetResponse,
|
||||
"thread/goal/get": CodexSchema.V2ThreadGoalGetResponse,
|
||||
"thread/goal/clear": CodexSchema.V2ThreadGoalClearResponse,
|
||||
"thread/metadata/update": CodexSchema.V2ThreadMetadataUpdateResponse,
|
||||
"thread/unarchive": CodexSchema.V2ThreadUnarchiveResponse,
|
||||
"thread/compact/start": CodexSchema.V2ThreadCompactStartResponse,
|
||||
@@ -529,16 +578,19 @@ export const CLIENT_REQUEST_RESPONSES = {
|
||||
"thread/read": CodexSchema.V2ThreadReadResponse,
|
||||
"thread/inject_items": CodexSchema.V2ThreadInjectItemsResponse,
|
||||
"skills/list": CodexSchema.V2SkillsListResponse,
|
||||
"skills/extraRoots/set": CodexSchema.V2SkillsExtraRootsSetResponse,
|
||||
"hooks/list": CodexSchema.V2HooksListResponse,
|
||||
"marketplace/add": CodexSchema.V2MarketplaceAddResponse,
|
||||
"marketplace/remove": CodexSchema.V2MarketplaceRemoveResponse,
|
||||
"marketplace/upgrade": CodexSchema.V2MarketplaceUpgradeResponse,
|
||||
"plugin/list": CodexSchema.V2PluginListResponse,
|
||||
"plugin/installed": CodexSchema.V2PluginInstalledResponse,
|
||||
"plugin/read": CodexSchema.V2PluginReadResponse,
|
||||
"plugin/skill/read": CodexSchema.V2PluginSkillReadResponse,
|
||||
"plugin/share/save": CodexSchema.V2PluginShareSaveResponse,
|
||||
"plugin/share/updateTargets": CodexSchema.V2PluginShareUpdateTargetsResponse,
|
||||
"plugin/share/list": CodexSchema.V2PluginShareListResponse,
|
||||
"plugin/share/checkout": CodexSchema.V2PluginShareCheckoutResponse,
|
||||
"plugin/share/delete": CodexSchema.V2PluginShareDeleteResponse,
|
||||
"app/list": CodexSchema.V2AppsListResponse,
|
||||
"fs/readFile": CodexSchema.V2FsReadFileResponse,
|
||||
@@ -560,6 +612,7 @@ export const CLIENT_REQUEST_RESPONSES = {
|
||||
"model/list": CodexSchema.V2ModelListResponse,
|
||||
"modelProvider/capabilities/read": CodexSchema.V2ModelProviderCapabilitiesReadResponse,
|
||||
"experimentalFeature/list": CodexSchema.V2ExperimentalFeatureListResponse,
|
||||
"permissionProfile/list": CodexSchema.V2PermissionProfileListResponse,
|
||||
"experimentalFeature/enablement/set": CodexSchema.V2ExperimentalFeatureEnablementSetResponse,
|
||||
"mcpServer/oauth/login": CodexSchema.V2McpServerOauthLoginResponse,
|
||||
"config/mcpServer/reload": CodexSchema.V2McpServerRefreshResponse,
|
||||
@@ -572,6 +625,7 @@ export const CLIENT_REQUEST_RESPONSES = {
|
||||
"account/login/cancel": CodexSchema.V2CancelLoginAccountResponse,
|
||||
"account/logout": CodexSchema.V2LogoutAccountResponse,
|
||||
"account/rateLimits/read": CodexSchema.V2GetAccountRateLimitsResponse,
|
||||
"account/usage/read": CodexSchema.V2GetAccountTokenUsageResponse,
|
||||
"account/sendAddCreditsNudgeEmail": CodexSchema.V2SendAddCreditsNudgeEmailResponse,
|
||||
"feedback/upload": CodexSchema.V2FeedbackUploadResponse,
|
||||
"command/exec": CodexSchema.V2CommandExecResponse,
|
||||
@@ -603,6 +657,7 @@ export const SERVER_REQUEST_PARAMS = {
|
||||
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalParams,
|
||||
"item/tool/call": CodexSchema.DynamicToolCallParams,
|
||||
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshParams,
|
||||
"attestation/generate": CodexSchema.AttestationGenerateParams,
|
||||
applyPatchApproval: CodexSchema.ApplyPatchApprovalParams,
|
||||
execCommandApproval: CodexSchema.ExecCommandApprovalParams,
|
||||
} as const;
|
||||
@@ -615,6 +670,7 @@ export const SERVER_REQUEST_RESPONSES = {
|
||||
"item/permissions/requestApproval": CodexSchema.PermissionsRequestApprovalResponse,
|
||||
"item/tool/call": CodexSchema.DynamicToolCallResponse,
|
||||
"account/chatgptAuthTokens/refresh": CodexSchema.ChatgptAuthTokensRefreshResponse,
|
||||
"attestation/generate": CodexSchema.AttestationGenerateResponse,
|
||||
applyPatchApproval: CodexSchema.ApplyPatchApprovalResponse,
|
||||
execCommandApproval: CodexSchema.ExecCommandApprovalResponse,
|
||||
} as const;
|
||||
@@ -624,12 +680,14 @@ export const SERVER_NOTIFICATION_PARAMS = {
|
||||
"thread/started": CodexSchema.V2ThreadStartedNotification,
|
||||
"thread/status/changed": CodexSchema.V2ThreadStatusChangedNotification,
|
||||
"thread/archived": CodexSchema.V2ThreadArchivedNotification,
|
||||
"thread/deleted": CodexSchema.V2ThreadDeletedNotification,
|
||||
"thread/unarchived": CodexSchema.V2ThreadUnarchivedNotification,
|
||||
"thread/closed": CodexSchema.V2ThreadClosedNotification,
|
||||
"skills/changed": CodexSchema.V2SkillsChangedNotification,
|
||||
"thread/name/updated": CodexSchema.V2ThreadNameUpdatedNotification,
|
||||
"thread/goal/updated": CodexSchema.V2ThreadGoalUpdatedNotification,
|
||||
"thread/goal/cleared": CodexSchema.V2ThreadGoalClearedNotification,
|
||||
"thread/settings/updated": CodexSchema.V2ThreadSettingsUpdatedNotification,
|
||||
"thread/tokenUsage/updated": CodexSchema.V2ThreadTokenUsageUpdatedNotification,
|
||||
"turn/started": CodexSchema.V2TurnStartedNotification,
|
||||
"hook/started": CodexSchema.V2HookStartedNotification,
|
||||
@@ -669,6 +727,7 @@ export const SERVER_NOTIFICATION_PARAMS = {
|
||||
"thread/compacted": CodexSchema.V2ContextCompactedNotification,
|
||||
"model/rerouted": CodexSchema.V2ModelReroutedNotification,
|
||||
"model/verification": CodexSchema.V2ModelVerificationNotification,
|
||||
"turn/moderationMetadata": CodexSchema.V2TurnModerationMetadataNotification,
|
||||
warning: CodexSchema.V2WarningNotification,
|
||||
guardianWarning: CodexSchema.V2GuardianWarningNotification,
|
||||
deprecationNotice: CodexSchema.V2DeprecationNoticeNotification,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// This file is generated by the effect-codex-app-server package. Do not edit manually.
|
||||
// Upstream protocol ref: 07b695190f30a450e4921f71f77473e564395c59
|
||||
// Upstream protocol ref: b39f943a634a6e7ba86c3d6e8cf6d5f35e612566
|
||||
|
||||
import * as CodexSchema from "./schema.gen.ts";
|
||||
|
||||
@@ -74,6 +74,7 @@ export const v2 = {
|
||||
GetAccountParams: CodexSchema.V2GetAccountParams,
|
||||
GetAccountRateLimitsResponse: CodexSchema.V2GetAccountRateLimitsResponse,
|
||||
GetAccountResponse: CodexSchema.V2GetAccountResponse,
|
||||
GetAccountTokenUsageResponse: CodexSchema.V2GetAccountTokenUsageResponse,
|
||||
GuardianWarningNotification: CodexSchema.V2GuardianWarningNotification,
|
||||
HookCompletedNotification: CodexSchema.V2HookCompletedNotification,
|
||||
HooksListParams: CodexSchema.V2HooksListParams,
|
||||
@@ -112,13 +113,19 @@ export const v2 = {
|
||||
ModelProviderCapabilitiesReadResponse: CodexSchema.V2ModelProviderCapabilitiesReadResponse,
|
||||
ModelReroutedNotification: CodexSchema.V2ModelReroutedNotification,
|
||||
ModelVerificationNotification: CodexSchema.V2ModelVerificationNotification,
|
||||
PermissionProfileListParams: CodexSchema.V2PermissionProfileListParams,
|
||||
PermissionProfileListResponse: CodexSchema.V2PermissionProfileListResponse,
|
||||
PlanDeltaNotification: CodexSchema.V2PlanDeltaNotification,
|
||||
PluginInstalledParams: CodexSchema.V2PluginInstalledParams,
|
||||
PluginInstalledResponse: CodexSchema.V2PluginInstalledResponse,
|
||||
PluginInstallParams: CodexSchema.V2PluginInstallParams,
|
||||
PluginInstallResponse: CodexSchema.V2PluginInstallResponse,
|
||||
PluginListParams: CodexSchema.V2PluginListParams,
|
||||
PluginListResponse: CodexSchema.V2PluginListResponse,
|
||||
PluginReadParams: CodexSchema.V2PluginReadParams,
|
||||
PluginReadResponse: CodexSchema.V2PluginReadResponse,
|
||||
PluginShareCheckoutParams: CodexSchema.V2PluginShareCheckoutParams,
|
||||
PluginShareCheckoutResponse: CodexSchema.V2PluginShareCheckoutResponse,
|
||||
PluginShareDeleteParams: CodexSchema.V2PluginShareDeleteParams,
|
||||
PluginShareDeleteResponse: CodexSchema.V2PluginShareDeleteResponse,
|
||||
PluginShareListParams: CodexSchema.V2PluginShareListParams,
|
||||
@@ -146,6 +153,8 @@ export const v2 = {
|
||||
SkillsChangedNotification: CodexSchema.V2SkillsChangedNotification,
|
||||
SkillsConfigWriteParams: CodexSchema.V2SkillsConfigWriteParams,
|
||||
SkillsConfigWriteResponse: CodexSchema.V2SkillsConfigWriteResponse,
|
||||
SkillsExtraRootsSetParams: CodexSchema.V2SkillsExtraRootsSetParams,
|
||||
SkillsExtraRootsSetResponse: CodexSchema.V2SkillsExtraRootsSetResponse,
|
||||
SkillsListParams: CodexSchema.V2SkillsListParams,
|
||||
SkillsListResponse: CodexSchema.V2SkillsListResponse,
|
||||
TerminalInteractionNotification: CodexSchema.V2TerminalInteractionNotification,
|
||||
@@ -158,9 +167,18 @@ export const v2 = {
|
||||
ThreadClosedNotification: CodexSchema.V2ThreadClosedNotification,
|
||||
ThreadCompactStartParams: CodexSchema.V2ThreadCompactStartParams,
|
||||
ThreadCompactStartResponse: CodexSchema.V2ThreadCompactStartResponse,
|
||||
ThreadDeletedNotification: CodexSchema.V2ThreadDeletedNotification,
|
||||
ThreadDeleteParams: CodexSchema.V2ThreadDeleteParams,
|
||||
ThreadDeleteResponse: CodexSchema.V2ThreadDeleteResponse,
|
||||
ThreadForkParams: CodexSchema.V2ThreadForkParams,
|
||||
ThreadForkResponse: CodexSchema.V2ThreadForkResponse,
|
||||
ThreadGoalClearedNotification: CodexSchema.V2ThreadGoalClearedNotification,
|
||||
ThreadGoalClearParams: CodexSchema.V2ThreadGoalClearParams,
|
||||
ThreadGoalClearResponse: CodexSchema.V2ThreadGoalClearResponse,
|
||||
ThreadGoalGetParams: CodexSchema.V2ThreadGoalGetParams,
|
||||
ThreadGoalGetResponse: CodexSchema.V2ThreadGoalGetResponse,
|
||||
ThreadGoalSetParams: CodexSchema.V2ThreadGoalSetParams,
|
||||
ThreadGoalSetResponse: CodexSchema.V2ThreadGoalSetResponse,
|
||||
ThreadGoalUpdatedNotification: CodexSchema.V2ThreadGoalUpdatedNotification,
|
||||
ThreadInjectItemsParams: CodexSchema.V2ThreadInjectItemsParams,
|
||||
ThreadInjectItemsResponse: CodexSchema.V2ThreadInjectItemsResponse,
|
||||
@@ -189,6 +207,7 @@ export const v2 = {
|
||||
ThreadRollbackResponse: CodexSchema.V2ThreadRollbackResponse,
|
||||
ThreadSetNameParams: CodexSchema.V2ThreadSetNameParams,
|
||||
ThreadSetNameResponse: CodexSchema.V2ThreadSetNameResponse,
|
||||
ThreadSettingsUpdatedNotification: CodexSchema.V2ThreadSettingsUpdatedNotification,
|
||||
ThreadShellCommandParams: CodexSchema.V2ThreadShellCommandParams,
|
||||
ThreadShellCommandResponse: CodexSchema.V2ThreadShellCommandResponse,
|
||||
ThreadStartedNotification: CodexSchema.V2ThreadStartedNotification,
|
||||
@@ -205,6 +224,7 @@ export const v2 = {
|
||||
TurnDiffUpdatedNotification: CodexSchema.V2TurnDiffUpdatedNotification,
|
||||
TurnInterruptParams: CodexSchema.V2TurnInterruptParams,
|
||||
TurnInterruptResponse: CodexSchema.V2TurnInterruptResponse,
|
||||
TurnModerationMetadataNotification: CodexSchema.V2TurnModerationMetadataNotification,
|
||||
TurnPlanUpdatedNotification: CodexSchema.V2TurnPlanUpdatedNotification,
|
||||
TurnStartedNotification: CodexSchema.V2TurnStartedNotification,
|
||||
TurnStartParams: CodexSchema.V2TurnStartParams,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -152,4 +152,41 @@ it.layer(NodeServices.layer)("effect-codex-app-server client", (it) => {
|
||||
assert.equal(initialized.userAgent, "mock-codex-app-server");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("drains command stderr so large diagnostics cannot block protocol responses", () =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const scope = yield* Scope.make();
|
||||
const clientLayer = CodexClient.layerCommand({
|
||||
command: "node",
|
||||
args: mockPeerArgs(yield* mockPeerPath),
|
||||
cwd: path.join(import.meta.dirname, ".."),
|
||||
env: {
|
||||
CODEX_APP_SERVER_TEST_STDERR_BYTES: String(512 * 1024),
|
||||
},
|
||||
});
|
||||
const context = yield* Layer.buildWithScope(clientLayer, scope);
|
||||
|
||||
const initialized = yield* Effect.gen(function* () {
|
||||
const client = yield* CodexClient.CodexAppServerClient;
|
||||
return yield* client.request("initialize", {
|
||||
clientInfo: {
|
||||
name: "effect-codex-app-server-test",
|
||||
title: "Effect Codex App Server Test",
|
||||
version: "0.0.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: true,
|
||||
optOutNotificationMethods: null,
|
||||
},
|
||||
});
|
||||
}).pipe(
|
||||
Effect.timeout("5 seconds"),
|
||||
Effect.provide(context),
|
||||
Effect.ensuring(Scope.close(scope, Exit.void)),
|
||||
);
|
||||
|
||||
assert.equal(initialized.userAgent, "mock-codex-app-server");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -4,6 +4,7 @@ import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Scope from "effect/Scope";
|
||||
import * as Stdio from "effect/Stdio";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as CodexRpc from "./_generated/meta.gen.ts";
|
||||
@@ -253,11 +254,15 @@ export const make = Effect.fn("effect-codex-app-server/CodexAppServerClient.make
|
||||
export const layerChildProcess = (
|
||||
handle: ChildProcessSpawner.ChildProcessHandle,
|
||||
options: CodexAppServerClientOptions = {},
|
||||
): Layer.Layer<CodexAppServerClient> => {
|
||||
const stdio = makeChildStdio(handle);
|
||||
const terminationError = makeTerminationError(handle);
|
||||
return Layer.effect(CodexAppServerClient, make(stdio, options, terminationError));
|
||||
};
|
||||
): Layer.Layer<CodexAppServerClient> =>
|
||||
Layer.effect(CodexAppServerClient, makeChildProcessClient(handle, options));
|
||||
|
||||
const makeChildProcessClient = Effect.fn(
|
||||
"effect-codex-app-server/CodexAppServerClient.makeChildProcessClient",
|
||||
)(function* (handle: ChildProcessSpawner.ChildProcessHandle, options: CodexAppServerClientOptions) {
|
||||
yield* Stream.runDrain(handle.stderr).pipe(Effect.ignore, Effect.forkScoped);
|
||||
return yield* make(makeChildStdio(handle), options, makeTerminationError(handle));
|
||||
});
|
||||
|
||||
export interface CodexAppServerCommandLayerOptions extends CodexAppServerClientOptions {
|
||||
readonly command: string;
|
||||
@@ -292,9 +297,5 @@ export const layerCommand = (
|
||||
}),
|
||||
),
|
||||
);
|
||||
}).pipe(
|
||||
Effect.flatMap((handle) =>
|
||||
make(makeChildStdio(handle), options, makeTerminationError(handle)),
|
||||
),
|
||||
),
|
||||
}).pipe(Effect.flatMap((handle) => makeChildProcessClient(handle, options))),
|
||||
);
|
||||
@@ -10,6 +10,8 @@ import { assert, it } from "@effect/vitest";
|
||||
|
||||
import * as CodexError from "./errors.ts";
|
||||
import * as CodexProtocol from "./protocol.ts";
|
||||
import * as CodexRpc from "./rpc.ts";
|
||||
import * as CodexSchema from "./schema.ts";
|
||||
import { makeInMemoryStdio } from "./_internal/stdio.ts";
|
||||
const encodeUnknownJsonString = Schema.encodeUnknownSync(Schema.UnknownFromJsonString);
|
||||
|
||||
@@ -18,8 +20,28 @@ const encoder = new TextEncoder();
|
||||
const encodeJsonl = (value: unknown) => encoder.encode(`${encodeUnknownJsonString(value)}\n`);
|
||||
|
||||
const decodeJson = Schema.decodeEffect(Schema.UnknownFromJsonString);
|
||||
const decodeAccountTokenUsageResponse = Schema.decodeUnknownEffect(
|
||||
CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("effect-codex-app-server protocol", (it) => {
|
||||
it.effect("maps account usage responses to the upstream token usage schema", () =>
|
||||
Effect.gen(function* () {
|
||||
assert.strictEqual(
|
||||
CodexRpc.CLIENT_REQUEST_RESPONSES["account/usage/read"],
|
||||
CodexSchema.V2GetAccountTokenUsageResponse,
|
||||
);
|
||||
const decoded = yield* decodeAccountTokenUsageResponse({
|
||||
dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
|
||||
summary: { lifetimeTokens: 42 },
|
||||
});
|
||||
assert.deepEqual(decoded, {
|
||||
dailyUsageBuckets: [{ startDate: "2026-06-10", tokens: 42 }],
|
||||
summary: { lifetimeTokens: 42 },
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"encodes requests without a jsonrpc field and routes inbound requests and notifications",
|
||||
() =>
|
||||
|
||||
@@ -34,6 +34,18 @@ const handleMethod = (message: Record<string, unknown>) => {
|
||||
|
||||
switch (method) {
|
||||
case "initialize": {
|
||||
const stderrBytes = Number(process.env.CODEX_APP_SERVER_TEST_STDERR_BYTES ?? 0);
|
||||
if (Number.isFinite(stderrBytes) && stderrBytes > 0) {
|
||||
process.stderr.write("x".repeat(stderrBytes), () => {
|
||||
respond(message.id as number | string, {
|
||||
userAgent: "mock-codex-app-server",
|
||||
codexHome: process.cwd(),
|
||||
platformFamily: process.platform === "win32" ? "windows" : "unix",
|
||||
platformOs: process.platform === "darwin" ? "macos" : process.platform,
|
||||
});
|
||||
});
|
||||
return;
|
||||
}
|
||||
respond(message.id as number | string, {
|
||||
userAgent: "mock-codex-app-server",
|
||||
codexHome: process.cwd(),
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import * as NodeCrypto from "node:crypto";
|
||||
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Option from "effect/Option";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
|
||||
import {
|
||||
computeDpopAccessTokenHash,
|
||||
computeDpopJwkThumbprint,
|
||||
normalizeDpopHtu,
|
||||
normalizeDpopHtuOption,
|
||||
type DpopPublicJwk,
|
||||
type DpopVerificationResult,
|
||||
verifyDpopProof,
|
||||
} from "./dpop.ts";
|
||||
|
||||
@@ -44,24 +41,6 @@ function signDpopProof(input: {
|
||||
return `${header}.${payload}.${signature}`;
|
||||
}
|
||||
|
||||
type DpopRejectedResult = Extract<DpopVerificationResult, { readonly ok: false }>;
|
||||
|
||||
function assertAccepted(result: DpopVerificationResult) {
|
||||
if (!result.ok) {
|
||||
assert.fail(`Expected accepted DPoP proof, got ${result.error._tag}`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function assertRejected(result: DpopVerificationResult, tag: DpopRejectedResult["error"]["_tag"]) {
|
||||
if (result.ok) {
|
||||
assert.fail("Expected rejected DPoP proof.");
|
||||
}
|
||||
assert.equal(result.error._tag, tag);
|
||||
assert.equal(result.reason, result.error.message);
|
||||
return result;
|
||||
}
|
||||
|
||||
describe("verifyDpopProof", () => {
|
||||
const { privateKey, publicKey } = NodeCrypto.generateKeyPairSync("ec", {
|
||||
namedCurve: "P-256",
|
||||
@@ -77,7 +56,7 @@ describe("verifyDpopProof", () => {
|
||||
|
||||
it("verifies an ES256 DPoP proof and returns the RFC 7638 thumbprint", () => {
|
||||
const thumbprint = computeDpopJwkThumbprint(publicJwk);
|
||||
const result = assertAccepted(
|
||||
expect(
|
||||
verifyDpopProof({
|
||||
proof,
|
||||
method: "POST",
|
||||
@@ -85,14 +64,16 @@ describe("verifyDpopProof", () => {
|
||||
nowEpochSeconds: 101,
|
||||
expectedThumbprint: thumbprint,
|
||||
}),
|
||||
);
|
||||
assert.equal(result.thumbprint, thumbprint);
|
||||
assert.equal(result.jti, "proof-1");
|
||||
).toMatchObject({
|
||||
ok: true,
|
||||
thumbprint,
|
||||
jti: "proof-1",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects method, URL, thumbprint, and time-window mismatches", () => {
|
||||
const thumbprint = computeDpopJwkThumbprint(publicJwk);
|
||||
assertRejected(
|
||||
expect(
|
||||
verifyDpopProof({
|
||||
proof,
|
||||
method: "GET",
|
||||
@@ -100,9 +81,8 @@ describe("verifyDpopProof", () => {
|
||||
nowEpochSeconds: 101,
|
||||
expectedThumbprint: thumbprint,
|
||||
}),
|
||||
"DpopMethodMismatchError",
|
||||
);
|
||||
assertRejected(
|
||||
).toMatchObject({ ok: false });
|
||||
expect(
|
||||
verifyDpopProof({
|
||||
proof,
|
||||
method: "POST",
|
||||
@@ -110,9 +90,8 @@ describe("verifyDpopProof", () => {
|
||||
nowEpochSeconds: 101,
|
||||
expectedThumbprint: thumbprint,
|
||||
}),
|
||||
"DpopUrlMismatchError",
|
||||
);
|
||||
assertRejected(
|
||||
).toMatchObject({ ok: false });
|
||||
expect(
|
||||
verifyDpopProof({
|
||||
proof,
|
||||
method: "POST",
|
||||
@@ -120,9 +99,8 @@ describe("verifyDpopProof", () => {
|
||||
nowEpochSeconds: 101,
|
||||
expectedThumbprint: "other-thumbprint",
|
||||
}),
|
||||
"DpopThumbprintMismatchError",
|
||||
);
|
||||
assertRejected(
|
||||
).toMatchObject({ ok: false });
|
||||
expect(
|
||||
verifyDpopProof({
|
||||
proof,
|
||||
method: "POST",
|
||||
@@ -130,8 +108,7 @@ describe("verifyDpopProof", () => {
|
||||
nowEpochSeconds: 1_000,
|
||||
expectedThumbprint: thumbprint,
|
||||
}),
|
||||
"DpopTimeWindowError",
|
||||
);
|
||||
).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it("requires the RFC 9449 access token hash when an access token is expected", () => {
|
||||
@@ -145,7 +122,7 @@ describe("verifyDpopProof", () => {
|
||||
accessToken: "clerk-access-token",
|
||||
});
|
||||
|
||||
assertAccepted(
|
||||
expect(
|
||||
verifyDpopProof({
|
||||
proof: accessTokenProof,
|
||||
method: "POST",
|
||||
@@ -154,8 +131,8 @@ describe("verifyDpopProof", () => {
|
||||
expectedThumbprint: thumbprint,
|
||||
expectedAccessToken: "clerk-access-token",
|
||||
}),
|
||||
);
|
||||
assertRejected(
|
||||
).toMatchObject({ ok: true });
|
||||
expect(
|
||||
verifyDpopProof({
|
||||
proof,
|
||||
method: "POST",
|
||||
@@ -164,9 +141,8 @@ describe("verifyDpopProof", () => {
|
||||
expectedThumbprint: thumbprint,
|
||||
expectedAccessToken: "clerk-access-token",
|
||||
}),
|
||||
"DpopAccessTokenHashMismatchError",
|
||||
);
|
||||
assertRejected(
|
||||
).toMatchObject({ ok: false, reason: "DPoP access token hash mismatch." });
|
||||
expect(
|
||||
verifyDpopProof({
|
||||
proof: accessTokenProof,
|
||||
method: "POST",
|
||||
@@ -175,20 +151,13 @@ describe("verifyDpopProof", () => {
|
||||
expectedThumbprint: thumbprint,
|
||||
expectedAccessToken: "other-access-token",
|
||||
}),
|
||||
"DpopAccessTokenHashMismatchError",
|
||||
);
|
||||
).toMatchObject({ ok: false, reason: "DPoP access token hash mismatch." });
|
||||
});
|
||||
|
||||
it("normalizes htu by excluding query and fragment components per RFC 9449", () => {
|
||||
assert.equal(
|
||||
normalizeDpopHtu("https://example.com/v1/environments/env/connect?foo=bar#frag"),
|
||||
expect(normalizeDpopHtu("https://example.com/v1/environments/env/connect?foo=bar#frag")).toBe(
|
||||
"https://example.com/v1/environments/env/connect",
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
normalizeDpopHtuOption("https://example.com/v1/environments/env/connect?foo=bar#frag"),
|
||||
Option.some("https://example.com/v1/environments/env/connect"),
|
||||
);
|
||||
assert.deepStrictEqual(normalizeDpopHtuOption("not a url"), Option.none());
|
||||
|
||||
const thumbprint = computeDpopJwkThumbprint(publicJwk);
|
||||
const queryProof = signDpopProof({
|
||||
@@ -199,7 +168,7 @@ describe("verifyDpopProof", () => {
|
||||
publicJwk,
|
||||
});
|
||||
|
||||
assertAccepted(
|
||||
expect(
|
||||
verifyDpopProof({
|
||||
proof: queryProof,
|
||||
method: "POST",
|
||||
@@ -207,7 +176,7 @@ describe("verifyDpopProof", () => {
|
||||
nowEpochSeconds: 101,
|
||||
expectedThumbprint: thumbprint,
|
||||
}),
|
||||
);
|
||||
).toMatchObject({ ok: true });
|
||||
});
|
||||
|
||||
it("rejects DPoP public JWK headers that expose private key material", () => {
|
||||
@@ -223,7 +192,7 @@ describe("verifyDpopProof", () => {
|
||||
publicJwk: privateJwk,
|
||||
});
|
||||
|
||||
assertRejected(
|
||||
expect(
|
||||
verifyDpopProof({
|
||||
proof: proofWithPrivateJwk,
|
||||
method: "POST",
|
||||
@@ -231,7 +200,6 @@ describe("verifyDpopProof", () => {
|
||||
nowEpochSeconds: 101,
|
||||
expectedThumbprint: thumbprint,
|
||||
}),
|
||||
"InvalidDpopJwtHeaderError",
|
||||
);
|
||||
).toMatchObject({ ok: false, reason: "Invalid DPoP JWT header." });
|
||||
});
|
||||
});
|
||||
+114
-277
@@ -1,160 +1,38 @@
|
||||
import { p256 } from "@noble/curves/nist";
|
||||
import { sha256 } from "@noble/hashes/sha2";
|
||||
import * as Encoding from "effect/Encoding";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Result from "effect/Result";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import { DpopPublicJwk as DpopPublicJwkSchema, normalizeDpopHtuOption } from "./dpopCommon.ts";
|
||||
import type { DpopPublicJwk as DpopPublicJwkType } from "./dpopCommon.ts";
|
||||
import { stableStringify } from "./relaySigning.ts";
|
||||
|
||||
export const DpopPublicJwk = DpopPublicJwkSchema;
|
||||
export type DpopPublicJwk = DpopPublicJwkType;
|
||||
export { normalizeDpopHtu, normalizeDpopHtuOption } from "./dpopCommon.ts";
|
||||
|
||||
const DPOP_TYP = "dpop+jwt";
|
||||
const DPOP_ALG = "ES256";
|
||||
const DEFAULT_MAX_AGE_SECONDS = 300;
|
||||
|
||||
const DpopJwtHeader = Schema.Struct({
|
||||
typ: Schema.Literal(DPOP_TYP),
|
||||
alg: Schema.Literal(DPOP_ALG),
|
||||
jwk: DpopPublicJwk,
|
||||
export const DpopPublicJwk = Schema.Struct({
|
||||
kty: Schema.Literal("EC"),
|
||||
crv: Schema.Literal("P-256"),
|
||||
x: Schema.String.check(Schema.isNonEmpty()),
|
||||
y: Schema.String.check(Schema.isNonEmpty()),
|
||||
});
|
||||
type DpopJwtHeader = typeof DpopJwtHeader.Type;
|
||||
export type DpopPublicJwk = typeof DpopPublicJwk.Type;
|
||||
const isDpopPublicJwk = Schema.is(DpopPublicJwk);
|
||||
|
||||
const DpopJwtPayload = Schema.Struct({
|
||||
htm: Schema.String.check(Schema.isNonEmpty()),
|
||||
htu: Schema.String.check(Schema.isNonEmpty()),
|
||||
jti: Schema.String.check(Schema.isNonEmpty()),
|
||||
iat: Schema.Int,
|
||||
ath: Schema.optionalKey(Schema.String),
|
||||
});
|
||||
type DpopJwtPayload = typeof DpopJwtPayload.Type;
|
||||
|
||||
const decodeDpopJwtHeaderJson = Schema.decodeUnknownOption(Schema.fromJsonString(DpopJwtHeader), {
|
||||
onExcessProperty: "preserve",
|
||||
});
|
||||
const decodeDpopJwtPayloadJson = Schema.decodeUnknownOption(Schema.fromJsonString(DpopJwtPayload));
|
||||
|
||||
export class MissingDpopProofError extends Schema.TaggedErrorClass<MissingDpopProofError>()(
|
||||
"MissingDpopProofError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Missing DPoP proof.";
|
||||
}
|
||||
interface DpopJwtHeader {
|
||||
readonly typ: string;
|
||||
readonly alg: string;
|
||||
readonly jwk: DpopPublicJwk;
|
||||
}
|
||||
|
||||
export class MalformedDpopCompactJwtError extends Schema.TaggedErrorClass<MalformedDpopCompactJwtError>()(
|
||||
"MalformedDpopCompactJwtError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Invalid DPoP compact JWT.";
|
||||
}
|
||||
interface DpopJwtPayload {
|
||||
readonly htm: string;
|
||||
readonly htu: string;
|
||||
readonly jti: string;
|
||||
readonly iat: number;
|
||||
readonly ath?: string;
|
||||
}
|
||||
|
||||
export class InvalidDpopJwtHeaderError extends Schema.TaggedErrorClass<InvalidDpopJwtHeaderError>()(
|
||||
"InvalidDpopJwtHeaderError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Invalid DPoP JWT header.";
|
||||
}
|
||||
}
|
||||
|
||||
export class InvalidDpopJwtPayloadError extends Schema.TaggedErrorClass<InvalidDpopJwtPayloadError>()(
|
||||
"InvalidDpopJwtPayloadError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Invalid DPoP JWT payload.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopThumbprintMismatchError extends Schema.TaggedErrorClass<DpopThumbprintMismatchError>()(
|
||||
"DpopThumbprintMismatchError",
|
||||
{
|
||||
expectedThumbprint: Schema.String,
|
||||
actualThumbprint: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "DPoP key thumbprint mismatch.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopMethodMismatchError extends Schema.TaggedErrorClass<DpopMethodMismatchError>()(
|
||||
"DpopMethodMismatchError",
|
||||
{
|
||||
expectedMethod: Schema.String,
|
||||
actualMethod: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "DPoP method mismatch.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopUrlMismatchError extends Schema.TaggedErrorClass<DpopUrlMismatchError>()(
|
||||
"DpopUrlMismatchError",
|
||||
{
|
||||
requestUrl: Schema.String,
|
||||
proofUrl: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "DPoP URL mismatch.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopAccessTokenHashMismatchError extends Schema.TaggedErrorClass<DpopAccessTokenHashMismatchError>()(
|
||||
"DpopAccessTokenHashMismatchError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "DPoP access token hash mismatch.";
|
||||
}
|
||||
}
|
||||
|
||||
export class DpopTimeWindowError extends Schema.TaggedErrorClass<DpopTimeWindowError>()(
|
||||
"DpopTimeWindowError",
|
||||
{
|
||||
iat: Schema.Int,
|
||||
nowEpochSeconds: Schema.Int,
|
||||
maxAgeSeconds: Schema.Int,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "DPoP proof is outside the allowed time window.";
|
||||
}
|
||||
}
|
||||
|
||||
export class InvalidDpopSignatureError extends Schema.TaggedErrorClass<InvalidDpopSignatureError>()(
|
||||
"InvalidDpopSignatureError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Invalid DPoP signature.";
|
||||
}
|
||||
}
|
||||
|
||||
export const DpopVerificationError = Schema.Union([
|
||||
MissingDpopProofError,
|
||||
MalformedDpopCompactJwtError,
|
||||
InvalidDpopJwtHeaderError,
|
||||
InvalidDpopJwtPayloadError,
|
||||
DpopThumbprintMismatchError,
|
||||
DpopMethodMismatchError,
|
||||
DpopUrlMismatchError,
|
||||
DpopAccessTokenHashMismatchError,
|
||||
DpopTimeWindowError,
|
||||
InvalidDpopSignatureError,
|
||||
]);
|
||||
export type DpopVerificationError = typeof DpopVerificationError.Type;
|
||||
|
||||
export type DpopVerificationResult =
|
||||
| {
|
||||
readonly ok: true;
|
||||
@@ -165,45 +43,45 @@ export type DpopVerificationResult =
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly reason: string;
|
||||
readonly error: DpopVerificationError;
|
||||
};
|
||||
|
||||
function rejectDpopProof(error: DpopVerificationError): DpopVerificationResult {
|
||||
return { ok: false, reason: error.message, error };
|
||||
function base64UrlToBytes(value: string): Uint8Array {
|
||||
return Result.getOrThrow(Encoding.decodeBase64Url(value));
|
||||
}
|
||||
|
||||
function compactJwtParts(proof: string): Option.Option<readonly [string, string, string]> {
|
||||
const parts = proof.split(".");
|
||||
return parts.length === 3 && parts[0] && parts[1] && parts[2]
|
||||
? Option.some([parts[0], parts[1], parts[2]] as const)
|
||||
: Option.none();
|
||||
function decodeBase64UrlJson(value: string): unknown {
|
||||
return JSON.parse(Result.getOrThrow(Encoding.decodeBase64UrlString(value))) as unknown;
|
||||
}
|
||||
|
||||
function base64UrlToBytesOption(value: string): Option.Option<Uint8Array> {
|
||||
const result = Encoding.decodeBase64Url(value);
|
||||
return Result.isSuccess(result) ? Option.some(result.success) : Option.none();
|
||||
function isDpopJwtHeader(value: unknown): value is DpopJwtHeader {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
return false;
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
return (
|
||||
record.typ === DPOP_TYP &&
|
||||
record.alg === DPOP_ALG &&
|
||||
typeof record.jwk === "object" &&
|
||||
record.jwk !== null &&
|
||||
!("d" in record.jwk) &&
|
||||
isDpopPublicJwk(record.jwk)
|
||||
);
|
||||
}
|
||||
|
||||
function base64UrlToStringOption(value: string): Option.Option<string> {
|
||||
const result = Encoding.decodeBase64UrlString(value);
|
||||
return Result.isSuccess(result) ? Option.some(result.success) : Option.none();
|
||||
}
|
||||
|
||||
function decodeBase64UrlJsonOption<A>(
|
||||
value: string,
|
||||
decodeJson: (input: unknown) => Option.Option<A>,
|
||||
): Option.Option<A> {
|
||||
return Option.flatMap(base64UrlToStringOption(value), decodeJson);
|
||||
}
|
||||
|
||||
function hasPrivateJwkMaterial(header: DpopJwtHeader): boolean {
|
||||
return "d" in header.jwk;
|
||||
}
|
||||
|
||||
function proofInput(input: { readonly proof: string | null | undefined }): Option.Option<string> {
|
||||
return Option.fromNullishOr(input.proof).pipe(
|
||||
Option.map((proof) => proof.trim()),
|
||||
Option.filter((proof) => proof.length > 0),
|
||||
function isDpopJwtPayload(value: unknown): value is DpopJwtPayload {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
return false;
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof record.htm === "string" &&
|
||||
record.htm.length > 0 &&
|
||||
typeof record.htu === "string" &&
|
||||
record.htu.length > 0 &&
|
||||
typeof record.jti === "string" &&
|
||||
record.jti.length > 0 &&
|
||||
typeof record.iat === "number" &&
|
||||
Number.isInteger(record.iat)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -216,6 +94,17 @@ function dpopThumbprintInput(jwk: DpopPublicJwk): string {
|
||||
});
|
||||
}
|
||||
|
||||
export function normalizeDpopHtu(url: string): string | null {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
parsed.hash = "";
|
||||
parsed.search = "";
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function computeDpopJwkThumbprint(jwk: DpopPublicJwk): string {
|
||||
return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(dpopThumbprintInput(jwk))));
|
||||
}
|
||||
@@ -224,20 +113,17 @@ export function computeDpopAccessTokenHash(accessToken: string): string {
|
||||
return Encoding.encodeBase64Url(sha256(new TextEncoder().encode(accessToken)));
|
||||
}
|
||||
|
||||
function publicKeyBytesFromJwkOption(jwk: DpopPublicJwk): Option.Option<Uint8Array> {
|
||||
const x = base64UrlToBytesOption(jwk.x);
|
||||
const y = base64UrlToBytesOption(jwk.y);
|
||||
if (Option.isNone(x) || Option.isNone(y)) {
|
||||
return Option.none();
|
||||
}
|
||||
if (x.value.length !== 32 || y.value.length !== 32) {
|
||||
return Option.none();
|
||||
function publicKeyBytesFromJwk(jwk: DpopPublicJwk): Uint8Array {
|
||||
const x = base64UrlToBytes(jwk.x);
|
||||
const y = base64UrlToBytes(jwk.y);
|
||||
if (x.length !== 32 || y.length !== 32) {
|
||||
throw new Error("Invalid P-256 public key coordinate length.");
|
||||
}
|
||||
const publicKey = new Uint8Array(65);
|
||||
publicKey[0] = 0x04;
|
||||
publicKey.set(x.value, 1);
|
||||
publicKey.set(y.value, 33);
|
||||
return Option.some(publicKey);
|
||||
publicKey.set(x, 1);
|
||||
publicKey.set(y, 33);
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
export function verifyDpopProof(input: {
|
||||
@@ -249,103 +135,54 @@ export function verifyDpopProof(input: {
|
||||
readonly expectedAccessToken?: string;
|
||||
readonly maxAgeSeconds?: number;
|
||||
}): DpopVerificationResult {
|
||||
const proof = proofInput(input);
|
||||
if (Option.isNone(proof)) {
|
||||
return rejectDpopProof(new MissingDpopProofError({}));
|
||||
if (!input.proof?.trim()) {
|
||||
return { ok: false, reason: "Missing DPoP proof." };
|
||||
}
|
||||
|
||||
const parts = compactJwtParts(proof.value);
|
||||
if (Option.isNone(parts)) {
|
||||
return rejectDpopProof(new MalformedDpopCompactJwtError({}));
|
||||
}
|
||||
|
||||
const [headerPart, payloadPart, signaturePart] = parts.value;
|
||||
const header = decodeBase64UrlJsonOption(headerPart, decodeDpopJwtHeaderJson);
|
||||
if (Option.isNone(header)) {
|
||||
return rejectDpopProof(new InvalidDpopJwtHeaderError({}));
|
||||
}
|
||||
if (hasPrivateJwkMaterial(header.value)) {
|
||||
return rejectDpopProof(new InvalidDpopJwtHeaderError({}));
|
||||
}
|
||||
|
||||
const payload = decodeBase64UrlJsonOption(payloadPart, decodeDpopJwtPayloadJson);
|
||||
if (Option.isNone(payload)) {
|
||||
return rejectDpopProof(new InvalidDpopJwtPayloadError({}));
|
||||
}
|
||||
|
||||
const publicKey = publicKeyBytesFromJwkOption(header.value.jwk);
|
||||
if (Option.isNone(publicKey)) {
|
||||
return rejectDpopProof(new InvalidDpopJwtHeaderError({}));
|
||||
}
|
||||
|
||||
const thumbprint = computeDpopJwkThumbprint(header.value.jwk);
|
||||
const expectedThumbprint = Option.fromUndefinedOr(input.expectedThumbprint);
|
||||
if (Option.isSome(expectedThumbprint) && thumbprint !== expectedThumbprint.value) {
|
||||
return rejectDpopProof(
|
||||
new DpopThumbprintMismatchError({
|
||||
expectedThumbprint: expectedThumbprint.value,
|
||||
actualThumbprint: thumbprint,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
if (payload.value.htm.toUpperCase() !== input.method.toUpperCase()) {
|
||||
return rejectDpopProof(
|
||||
new DpopMethodMismatchError({
|
||||
expectedMethod: input.method,
|
||||
actualMethod: payload.value.htm,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const normalizedHtu = normalizeDpopHtuOption(input.url);
|
||||
if (Option.isNone(normalizedHtu)) {
|
||||
return rejectDpopProof(
|
||||
new DpopUrlMismatchError({
|
||||
requestUrl: input.url,
|
||||
proofUrl: payload.value.htu,
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (payload.value.htu !== normalizedHtu.value) {
|
||||
return rejectDpopProof(
|
||||
new DpopUrlMismatchError({
|
||||
requestUrl: input.url,
|
||||
proofUrl: payload.value.htu,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const expectedAccessToken = Option.fromUndefinedOr(input.expectedAccessToken);
|
||||
if (Option.isSome(expectedAccessToken)) {
|
||||
const expectedAth = computeDpopAccessTokenHash(expectedAccessToken.value);
|
||||
if (payload.value.ath !== expectedAth) {
|
||||
return rejectDpopProof(new DpopAccessTokenHashMismatchError({}));
|
||||
}
|
||||
}
|
||||
|
||||
const maxAgeSeconds = input.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS;
|
||||
if (
|
||||
payload.value.iat > input.nowEpochSeconds + 5 ||
|
||||
input.nowEpochSeconds - payload.value.iat > maxAgeSeconds
|
||||
) {
|
||||
return rejectDpopProof(
|
||||
new DpopTimeWindowError({
|
||||
iat: payload.value.iat,
|
||||
nowEpochSeconds: input.nowEpochSeconds,
|
||||
maxAgeSeconds,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const signature = base64UrlToBytesOption(signaturePart);
|
||||
if (Option.isNone(signature)) {
|
||||
return rejectDpopProof(new InvalidDpopSignatureError({}));
|
||||
const parts = input.proof.split(".");
|
||||
if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {
|
||||
return { ok: false, reason: "Invalid DPoP compact JWT." };
|
||||
}
|
||||
|
||||
try {
|
||||
const signatureInputHash = sha256(new TextEncoder().encode(`${headerPart}.${payloadPart}`));
|
||||
const verified = p256.verify(signature.value, signatureInputHash, publicKey.value, {
|
||||
const header = decodeBase64UrlJson(parts[0]);
|
||||
const payload = decodeBase64UrlJson(parts[1]);
|
||||
if (!isDpopJwtHeader(header)) {
|
||||
return { ok: false, reason: "Invalid DPoP JWT header." };
|
||||
}
|
||||
if (!isDpopJwtPayload(payload)) {
|
||||
return { ok: false, reason: "Invalid DPoP JWT payload." };
|
||||
}
|
||||
|
||||
const thumbprint = computeDpopJwkThumbprint(header.jwk);
|
||||
if (input.expectedThumbprint && thumbprint !== input.expectedThumbprint) {
|
||||
return { ok: false, reason: "DPoP key thumbprint mismatch." };
|
||||
}
|
||||
if (payload.htm.toUpperCase() !== input.method.toUpperCase()) {
|
||||
return { ok: false, reason: "DPoP method mismatch." };
|
||||
}
|
||||
const normalizedHtu = normalizeDpopHtu(input.url);
|
||||
if (normalizedHtu === null || payload.htu !== normalizedHtu) {
|
||||
return { ok: false, reason: "DPoP URL mismatch." };
|
||||
}
|
||||
if (input.expectedAccessToken) {
|
||||
const expectedAth = computeDpopAccessTokenHash(input.expectedAccessToken);
|
||||
if (payload.ath !== expectedAth) {
|
||||
return { ok: false, reason: "DPoP access token hash mismatch." };
|
||||
}
|
||||
}
|
||||
|
||||
const maxAgeSeconds = input.maxAgeSeconds ?? DEFAULT_MAX_AGE_SECONDS;
|
||||
if (
|
||||
payload.iat > input.nowEpochSeconds + 5 ||
|
||||
input.nowEpochSeconds - payload.iat > maxAgeSeconds
|
||||
) {
|
||||
return { ok: false, reason: "DPoP proof is outside the allowed time window." };
|
||||
}
|
||||
|
||||
const signature = base64UrlToBytes(parts[2]);
|
||||
const signatureInputHash = sha256(new TextEncoder().encode(`${parts[0]}.${parts[1]}`));
|
||||
const verified = p256.verify(signature, signatureInputHash, publicKeyBytesFromJwk(header.jwk), {
|
||||
prehash: false,
|
||||
format: "compact",
|
||||
});
|
||||
@@ -353,11 +190,11 @@ export function verifyDpopProof(input: {
|
||||
? {
|
||||
ok: true,
|
||||
thumbprint,
|
||||
jti: payload.value.jti,
|
||||
iat: payload.value.iat,
|
||||
jti: payload.jti,
|
||||
iat: payload.iat,
|
||||
}
|
||||
: rejectDpopProof(new InvalidDpopSignatureError({}));
|
||||
: { ok: false, reason: "Invalid DPoP signature." };
|
||||
} catch {
|
||||
return rejectDpopProof(new InvalidDpopSignatureError({}));
|
||||
return { ok: false, reason: "Invalid DPoP proof." };
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
export const DpopPublicJwk = Schema.Struct({
|
||||
@@ -9,17 +8,13 @@ export const DpopPublicJwk = Schema.Struct({
|
||||
});
|
||||
export type DpopPublicJwk = typeof DpopPublicJwk.Type;
|
||||
|
||||
export function normalizeDpopHtuOption(url: string): Option.Option<string> {
|
||||
export function normalizeDpopHtu(url: string): string | null {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
parsed.hash = "";
|
||||
parsed.search = "";
|
||||
return Option.some(parsed.toString());
|
||||
return parsed.toString();
|
||||
} catch {
|
||||
return Option.none();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeDpopHtu(url: string): string | null {
|
||||
return Option.getOrNull(normalizeDpopHtuOption(url));
|
||||
}
|
||||
Generated
+71
-51
@@ -50,6 +50,7 @@ overrides:
|
||||
'@effect/vitest': 4.0.0-beta.78
|
||||
'@effect/vitest>@vitest/runner': '-'
|
||||
'@effect/vitest>vitest': '-'
|
||||
'@expo/metro-config': 56.0.13
|
||||
'@types/node': 24.12.4
|
||||
effect: 4.0.0-beta.78
|
||||
vite: npm:@voidzero-dev/[email protected]
|
||||
@@ -371,8 +372,8 @@ importers:
|
||||
apps/server:
|
||||
dependencies:
|
||||
'@anthropic-ai/claude-agent-sdk':
|
||||
specifier: ^0.3.154
|
||||
version: 0.3.159(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])
|
||||
specifier: ^0.3.170
|
||||
version: 0.3.170(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])
|
||||
'@effect/platform-bun':
|
||||
specifier: 4.0.0-beta.78
|
||||
version: 4.0.0-beta.78([email protected])([email protected](patch_hash=883249d8efbb462e928e21fefef96027b66aec50751178cafdce45f08eee3754))([email protected])
|
||||
@@ -854,48 +855,48 @@ packages:
|
||||
'@alchemy.run/[email protected]':
|
||||
resolution: {integrity: sha512-TiIhPXCTCi3tk0zmdYJJ14CNSesSfsJxXdIOP0HTSItQ1mZWLocrF7qCuEWKyW/IEFzp6kaiOf19aIA/mbCp1g==}
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
resolution: {integrity: sha512-3nnH4yUNJVSyaU5DBlGw2yxc4zlnVvAnc9UOe+La47QVG7/dN+rWAgn4zCbqKk9bWFLDQ1Ek0r56EZE1Qo4UKQ==}
|
||||
'@anthropic-ai/[email protected]70':
|
||||
resolution: {integrity: sha512-rwfgArIa5WI0QPNqFsRBgvtSI0mrtpynUm0oK6+l6/KX4hcgnYGEzciZR1bOeD9/7sSZlTdIgt+T9alKeZmXcg==}
|
||||
cpu: [arm64]
|
||||
os: [darwin]
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
resolution: {integrity: sha512-iv+NRjz+t4Q1R2+kLdDbccSo3b0wedVJ9jMT3noznOVojZHzgkxVpTvt36/XkXV0rqIDQ5H18bBYIZZzOXu7mg==}
|
||||
'@anthropic-ai/[email protected]70':
|
||||
resolution: {integrity: sha512-0e58h8UQMtsQxLGIv9r4foxfBFWKZ7NeDtoplLhuD7EwQonehomw1sBXCch77t/IfUS+q5vQ5zv+fOGmap5nLQ==}
|
||||
cpu: [x64]
|
||||
os: [darwin]
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
resolution: {integrity: sha512-WvwiQBWt3tdu5EwqjpDZszI6p2uetYsw4Cxc6ptO/SmLIYXcDienP8nmirZdsZrS+Gzk6imgY0IY5mmNaRhelQ==}
|
||||
'@anthropic-ai/[email protected]70':
|
||||
resolution: {integrity: sha512-SRYfQcsXlOq+CD/FqkQBTSHbaD++w73GnnO+NUV9adLYrca3kfetRwWT1iguY1cNS0l34dCR3rlzCPq78vg1Jg==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
resolution: {integrity: sha512-FlsS5M4GCpzsQVaNDFF8dRgFGR3QwyAHZFl/xM/2Y2BqVBH+NH17RpKQSJxr1qr41QnsNkinMnu2iSKoc33hKg==}
|
||||
'@anthropic-ai/[email protected]70':
|
||||
resolution: {integrity: sha512-gLbaFqcGppFJQd4DLNV4IXoeahejT/p2/M8bSSvRDbla9GOsBr1AxV5XLRyBn1e7xFGozZIAIQr3+1chp7NJgQ==}
|
||||
cpu: [arm64]
|
||||
os: [linux]
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
resolution: {integrity: sha512-kFH6RC2YJbPc8XWRNy/wL4YU7LzdJjSwAdH488sVzIif3q+TrvVrV5y/IW0+MLmta+CKIqtFYpGaucsJYvj7Eg==}
|
||||
'@anthropic-ai/[email protected]70':
|
||||
resolution: {integrity: sha512-m4+I0qBEk7cxRKS+pL+eoWXbXTFOAo83fQ0tQvap4z/mDMm06IWJtEPoYTaMBwsp32GJWLkHWKbZSBCHZnp2DQ==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
resolution: {integrity: sha512-uNPEC/iRzVb4bEdzs0KAz1zV7i1PVGEZZnJTQyi1OtgVa81sAoH/H0CbbzDiTsquKdaESf+1DSSEkUlfZmMUEw==}
|
||||
'@anthropic-ai/[email protected]70':
|
||||
resolution: {integrity: sha512-Xl/m7TaSC3T5IDBdHrZQ9fCQYyDmPELN34CL+MoyPIf7uSmuZnjE9fUOqDh2Rv26JxWssi1M6X+BBvVuKd6Cpg==}
|
||||
cpu: [x64]
|
||||
os: [linux]
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
resolution: {integrity: sha512-WN1QEZGgWXz9GMl61QU6j9E+LEF5plki87bL2xsGwuCPzK+OeVPQU55pabuP8P+vFBFHUo3Y9OlTVyZHnUzmAQ==}
|
||||
'@anthropic-ai/[email protected]70':
|
||||
resolution: {integrity: sha512-IG+8isJNNJKbnnhO7m+PGhfVCg+XoQ/MDxGde5eigFI0WsEfitjuWSWwx82bT9ghxI1aa6qNvI+UPgPcZuo5Fg==}
|
||||
cpu: [arm64]
|
||||
os: [win32]
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
resolution: {integrity: sha512-Ty4seccD+dTDX5hhj89IUELZd/LkxO5O43Uiz5Mo8ZJktoX38SK4XMZlBS935QdqTFLRvPL0hvK4Lt4dTOqzPw==}
|
||||
'@anthropic-ai/[email protected]70':
|
||||
resolution: {integrity: sha512-7cuqSKbHVItPGVwRbd3A0BEJwcNtc7Fhoh6qHN4C6yrmjSrvdYYx3MLvq/VI768/RoG7mAMDxb+j7WfEfoP9BA==}
|
||||
cpu: [x64]
|
||||
os: [win32]
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
resolution: {integrity: sha512-Xh1oVMIK6N3KsiNIhqNH8ZK90zjRmAEL9d1Md8ZlGdHJE+HhdMYdBadujc3KEkV0uufsEUvYp+A3fDenfypGSA==}
|
||||
'@anthropic-ai/[email protected]70':
|
||||
resolution: {integrity: sha512-pAvhfk+iTodXZ6RF18Kz7BEUWFjL7EcR3tKuhUNdPpE1NAYCR3mSHGbafi72JsrNwKEDIs7FU31z3fqhwy8QzA==}
|
||||
engines: {node: '>=18.0.0'}
|
||||
peerDependencies:
|
||||
'@anthropic-ai/sdk': '>=0.93.0'
|
||||
@@ -2809,6 +2810,12 @@ packages:
|
||||
'@emnapi/core': ^1.7.1
|
||||
'@emnapi/runtime': ^1.7.1
|
||||
|
||||
'@napi-rs/[email protected]':
|
||||
resolution: {integrity: sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==}
|
||||
peerDependencies:
|
||||
'@emnapi/core': ^1.7.1
|
||||
'@emnapi/runtime': ^1.7.1
|
||||
|
||||
'@neon-rs/[email protected]':
|
||||
resolution: {integrity: sha512-kTPhdZyTQxB+2wpiRcFWrDcejc4JI6tkPuS7UZCG4l6Zvc5kU/gGQ/ozvHTh1XR5tS+UlfAfGuPajjzQjCiHCw==}
|
||||
|
||||
@@ -6534,8 +6541,8 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-/gGivxi8JPKWNm/W0jSmzcMPpfpPLc3dY/6GxhX2hQ9iGj3aDfklV4ET7NjKpSinLpJ5vafa9iiGIEZg10SfBw==}
|
||||
|
||||
[email protected]3:
|
||||
resolution: {integrity: sha512-eIaZ9qDgu7XV0pxOCrg7/WhnQ6Ivm22UcxhXx/A3dcbqbbYgBEkc6e/J/s7j2tS96zoB0S9VBdLwQNCWwUo4LA==}
|
||||
[email protected]5:
|
||||
resolution: {integrity: sha512-2NFaIyNVgJmBs/ecmtGzlmluTFs5cHEWGTdu0t1HBwYzoGXOL5nUQBRMXsXWla5i4KkG//QMzVP88m1+I3fdAQ==}
|
||||
engines: {node: '>=16.9.0'}
|
||||
|
||||
[email protected]:
|
||||
@@ -7689,6 +7696,10 @@ packages:
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-AWGB9WFcRXOQs48Z/udjI5ZcZMHXwX8XPByNpOydgcGsDLIzjGizhoMWJyKAWze7AVW/2W1i+/gPX4YtKe5cyg==}
|
||||
engines: {node: '>=12.20.0'}
|
||||
|
||||
[email protected]:
|
||||
resolution: {integrity: sha512-2W4oUZlVaqAPAil6FUg/difl6YhqhUR7x2eZY4bQCko22UXg3hptq9KLQdqFClV+Wu85UX7hNtdGTngi/1BxcA==}
|
||||
|
||||
@@ -8627,8 +8638,8 @@ packages:
|
||||
resolution: {integrity: sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
[email protected].0:
|
||||
resolution: {integrity: sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==}
|
||||
[email protected].1:
|
||||
resolution: {integrity: sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==}
|
||||
engines: {node: '>= 0.4'}
|
||||
|
||||
[email protected]:
|
||||
@@ -9673,44 +9684,44 @@ snapshots:
|
||||
|
||||
'@alchemy.run/[email protected]': {}
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
'@anthropic-ai/[email protected]70':
|
||||
optional: true
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
'@anthropic-ai/[email protected]70':
|
||||
optional: true
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
'@anthropic-ai/[email protected]70':
|
||||
optional: true
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
'@anthropic-ai/[email protected]70':
|
||||
optional: true
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
'@anthropic-ai/[email protected]70':
|
||||
optional: true
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
'@anthropic-ai/[email protected]70':
|
||||
optional: true
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
'@anthropic-ai/[email protected]70':
|
||||
optional: true
|
||||
|
||||
'@anthropic-ai/[email protected]59':
|
||||
'@anthropic-ai/[email protected]70':
|
||||
optional: true
|
||||
|
||||
'@anthropic-ai/[email protected]59(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])':
|
||||
'@anthropic-ai/[email protected]70(@anthropic-ai/[email protected]([email protected]))(@modelcontextprotocol/[email protected]([email protected]))([email protected])':
|
||||
dependencies:
|
||||
'@anthropic-ai/sdk': 0.93.0([email protected])
|
||||
'@modelcontextprotocol/sdk': 1.29.0([email protected])
|
||||
zod: 4.4.3
|
||||
optionalDependencies:
|
||||
'@anthropic-ai/claude-agent-sdk-darwin-arm64': 0.3.159
|
||||
'@anthropic-ai/claude-agent-sdk-darwin-x64': 0.3.159
|
||||
'@anthropic-ai/claude-agent-sdk-linux-arm64': 0.3.159
|
||||
'@anthropic-ai/claude-agent-sdk-linux-arm64-musl': 0.3.159
|
||||
'@anthropic-ai/claude-agent-sdk-linux-x64': 0.3.159
|
||||
'@anthropic-ai/claude-agent-sdk-linux-x64-musl': 0.3.159
|
||||
'@anthropic-ai/claude-agent-sdk-win32-arm64': 0.3.159
|
||||
'@anthropic-ai/claude-agent-sdk-win32-x64': 0.3.159
|
||||
'@anthropic-ai/claude-agent-sdk-darwin-arm64': 0.3.170
|
||||
'@anthropic-ai/claude-agent-sdk-darwin-x64': 0.3.170
|
||||
'@anthropic-ai/claude-agent-sdk-linux-arm64': 0.3.170
|
||||
'@anthropic-ai/claude-agent-sdk-linux-arm64-musl': 0.3.170
|
||||
'@anthropic-ai/claude-agent-sdk-linux-x64': 0.3.170
|
||||
'@anthropic-ai/claude-agent-sdk-linux-x64-musl': 0.3.170
|
||||
'@anthropic-ai/claude-agent-sdk-win32-arm64': 0.3.170
|
||||
'@anthropic-ai/claude-agent-sdk-win32-x64': 0.3.170
|
||||
|
||||
'@anthropic-ai/[email protected]([email protected])':
|
||||
dependencies:
|
||||
@@ -11606,9 +11617,9 @@ snapshots:
|
||||
|
||||
'@formkit/[email protected]': {}
|
||||
|
||||
'@hono/[email protected]([email protected]3)':
|
||||
'@hono/[email protected]([email protected]5)':
|
||||
dependencies:
|
||||
hono: 4.12.23
|
||||
hono: 4.12.25
|
||||
|
||||
'@img/[email protected]':
|
||||
optional: true
|
||||
@@ -12031,7 +12042,7 @@ snapshots:
|
||||
|
||||
'@modelcontextprotocol/[email protected]([email protected])':
|
||||
dependencies:
|
||||
'@hono/node-server': 1.19.14([email protected]3)
|
||||
'@hono/node-server': 1.19.14([email protected]5)
|
||||
ajv: 8.20.0
|
||||
ajv-formats: 3.0.1([email protected])
|
||||
content-type: 1.0.5
|
||||
@@ -12041,7 +12052,7 @@ snapshots:
|
||||
eventsource-parser: 3.1.0
|
||||
express: 5.2.1
|
||||
express-rate-limit: 8.5.2([email protected])
|
||||
hono: 4.12.23
|
||||
hono: 4.12.25
|
||||
jose: 6.2.3
|
||||
json-schema-typed: 8.0.2
|
||||
pkce-challenge: 5.0.1
|
||||
@@ -12085,6 +12096,13 @@ snapshots:
|
||||
'@tybys/wasm-util': 0.10.2
|
||||
optional: true
|
||||
|
||||
'@napi-rs/[email protected](@emnapi/[email protected])(@emnapi/[email protected])':
|
||||
dependencies:
|
||||
'@emnapi/core': 1.10.0
|
||||
'@emnapi/runtime': 1.10.0
|
||||
'@tybys/wasm-util': 0.10.2
|
||||
optional: true
|
||||
|
||||
'@neon-rs/[email protected]': {}
|
||||
|
||||
'@noble/[email protected]':
|
||||
@@ -12818,7 +12836,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@emnapi/core': 1.10.0
|
||||
'@emnapi/runtime': 1.10.0
|
||||
'@napi-rs/wasm-runtime': 1.1.4(@emnapi/[email protected])(@emnapi/[email protected])
|
||||
'@napi-rs/wasm-runtime': 1.1.5(@emnapi/[email protected])(@emnapi/[email protected])
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
@@ -12832,7 +12850,7 @@ snapshots:
|
||||
dependencies:
|
||||
'@emnapi/core': 1.10.0
|
||||
'@emnapi/runtime': 1.10.0
|
||||
'@napi-rs/wasm-runtime': 1.1.4(@emnapi/[email protected])(@emnapi/[email protected])
|
||||
'@napi-rs/wasm-runtime': 1.1.5(@emnapi/[email protected])(@emnapi/[email protected])
|
||||
optional: true
|
||||
|
||||
'@rolldown/[email protected]':
|
||||
@@ -15896,7 +15914,7 @@ snapshots:
|
||||
dependencies:
|
||||
react-is: 16.13.1
|
||||
|
||||
[email protected]3: {}
|
||||
[email protected]5: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -17258,6 +17276,8 @@ snapshots:
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]: {}
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
destr: 2.0.5
|
||||
@@ -17645,7 +17665,7 @@ snapshots:
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
side-channel: 1.1.0
|
||||
side-channel: 1.1.1
|
||||
|
||||
[email protected]:
|
||||
dependencies:
|
||||
@@ -18439,7 +18459,7 @@ snapshots:
|
||||
object-inspect: 1.13.4
|
||||
side-channel-map: 1.0.1
|
||||
|
||||
[email protected].0:
|
||||
[email protected].1:
|
||||
dependencies:
|
||||
es-errors: 1.3.0
|
||||
object-inspect: 1.13.4
|
||||
@@ -19071,7 +19091,7 @@ snapshots:
|
||||
es-module-lexer: 2.1.0
|
||||
expect-type: 1.3.0
|
||||
magic-string: 0.30.21
|
||||
obug: 2.1.1
|
||||
obug: 2.1.2
|
||||
pathe: 2.0.3
|
||||
picomatch: 4.0.4
|
||||
std-env: 4.1.0
|
||||
|
||||
@@ -56,6 +56,10 @@ overrides:
|
||||
"@effect/vitest": "catalog:"
|
||||
"@effect/vitest>@vitest/runner": "-"
|
||||
"@effect/vitest>vitest": "-"
|
||||
# Pinned to the version the patch in patchedDependencies targets — a fresh
|
||||
# resolve (e.g. release-smoke regenerating the lockfile) must not drift to a
|
||||
# newer release and orphan the patch (ERR_PNPM_UNUSED_PATCH).
|
||||
"@expo/metro-config": "56.0.13"
|
||||
"@types/node": "catalog:"
|
||||
effect: "catalog:"
|
||||
vite: "catalog:"
|
||||
|
||||
Reference in new issue
Block a user