Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3bec3d2c8d | ||
|
|
b24b5fb8ce | ||
|
|
0be82d3443 | ||
|
|
7a1b982926 | ||
|
|
062c809aa0 | ||
|
|
b8fba18575 | ||
|
|
f1f234d2a0 | ||
|
|
18f19a6fe8 | ||
|
|
efa6d97da0 | ||
|
|
5804697e92 | ||
|
|
9132c37c86 | ||
|
|
b9c7ea0581 | ||
|
|
556a195c9d | ||
|
|
80b282ece7 | ||
|
|
d15075b32d | ||
|
|
9f6686a13d | ||
|
|
c6ff7c0d5b | ||
|
|
a9e5a84c03 | ||
|
|
67ca528fea | ||
|
|
6d9b21c5d0 | ||
|
|
ddffdfc095 | ||
|
|
a58290ed79 | ||
|
|
3488ca3570 | ||
|
|
c542ce3369 | ||
|
|
15f0be848d | ||
|
|
1c3fa67374 | ||
|
|
0ac59d569d |
No files matched your search
@@ -21,3 +21,4 @@ apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
artifacts/
|
||||
@@ -45,6 +45,10 @@ We are very very early in this project. Expect bugs.
|
||||
|
||||
We are not accepting contributions yet.
|
||||
|
||||
## Performance benchmarks
|
||||
|
||||
See [docs/perf-benchmarks.md](./docs/perf-benchmarks.md) for the local perf harness, seeded scenarios, artifact format, and the commands for automated and manual benchmark runs.
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
@@ -488,7 +488,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEvents),
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEvents);
|
||||
},
|
||||
};
|
||||
|
||||
const queueTurnResponse = (
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { PERF_CATALOG_IDS, getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { seedPerfState } from "./seedPerfState.ts";
|
||||
|
||||
describe("seedPerfState", () => {
|
||||
const runParentDirsToCleanup: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
runParentDirsToCleanup
|
||||
.splice(0)
|
||||
.map((runParentDir) => rm(runParentDir, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("seeds large thread fixtures through the real event store and projection pipeline", async () => {
|
||||
const seeded = await seedPerfState("large_threads");
|
||||
runParentDirsToCleanup.push(seeded.runParentDir);
|
||||
const scenario = getPerfSeedScenario("large_threads");
|
||||
|
||||
expect(seeded.snapshot.projects).toHaveLength(5);
|
||||
expect(seeded.snapshot.threads).toHaveLength(30);
|
||||
expect(seeded.baseDir).toBe(join(seeded.runParentDir, "base"));
|
||||
expect(new Set(seeded.snapshot.threads.map((thread) => thread.projectId)).size).toBe(5);
|
||||
|
||||
const heavyThread = seeded.snapshot.threads.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
const heavyThreadScenario = scenario.threads.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
expect(heavyThread?.messages).toHaveLength(2_000);
|
||||
expect(heavyThreadScenario?.turnCount ?? Number.POSITIVE_INFINITY).toBeLessThan(100);
|
||||
expect((heavyThread?.activities.length ?? 0) > 0).toBe(true);
|
||||
expect((heavyThread?.proposedPlans.length ?? 0) > 0).toBe(true);
|
||||
expect((heavyThread?.checkpoints.length ?? 0) >= 20).toBe(true);
|
||||
expect((heavyThread?.checkpoints[0]?.files.length ?? 0) >= 12).toBe(true);
|
||||
});
|
||||
|
||||
it("enables assistant streaming in the burst base seed for websocket perf runs", async () => {
|
||||
const seeded = await seedPerfState("burst_base");
|
||||
runParentDirsToCleanup.push(seeded.runParentDir);
|
||||
|
||||
const rawSettings = await readFile(join(seeded.baseDir, "userdata/settings.json"), "utf8");
|
||||
expect(JSON.parse(rawSettings)).toMatchObject({
|
||||
enableAssistantStreaming: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,589 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { cp, mkdir, mkdtemp, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
CheckpointRef,
|
||||
CommandId,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationReadModel,
|
||||
type ProjectId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, ManagedRuntime } from "effect";
|
||||
|
||||
import {
|
||||
buildPerfAssistantMessageCountPlan,
|
||||
getPerfSeedScenario,
|
||||
perfEventId,
|
||||
perfMessageIdForThread,
|
||||
perfTurnIdForThread,
|
||||
type PerfProjectScenario,
|
||||
type PerfSeedScenario,
|
||||
type PerfSeedScenarioId,
|
||||
type PerfSeedThreadScenario,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { ServerConfig } from "../../src/config.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationProjectionPipeline } from "../../src/orchestration/Services/ProjectionPipeline.ts";
|
||||
import { ProjectionSnapshotQuery } from "../../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../../src/persistence/Layers/Sqlite.ts";
|
||||
import { OrchestrationEventStore } from "../../src/persistence/Services/OrchestrationEventStore.ts";
|
||||
import { ServerSettingsService, ServerSettingsLive } from "../../src/serverSettings.ts";
|
||||
|
||||
export interface PerfSeededState {
|
||||
readonly scenarioId: PerfSeedScenarioId;
|
||||
readonly runParentDir: string;
|
||||
readonly baseDir: string;
|
||||
readonly workspaceRoot: string;
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
}
|
||||
|
||||
const templateDirPromises = new Map<PerfSeedScenarioId, Promise<string>>();
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
execFileSync("git", args, {
|
||||
cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
async function initializeGitWorkspace(workspaceRoot: string): Promise<void> {
|
||||
await mkdir(workspaceRoot, { recursive: true });
|
||||
runGit(workspaceRoot, ["init", "--initial-branch=main"]);
|
||||
runGit(workspaceRoot, ["config", "user.email", "[email protected]"]);
|
||||
runGit(workspaceRoot, ["config", "user.name", "Perf Fixture"]);
|
||||
await writeFile(
|
||||
join(workspaceRoot, "README.md"),
|
||||
"# Performance Workspace\n\nSeeded fixture state for local perf regression tests.\n",
|
||||
"utf8",
|
||||
);
|
||||
runGit(workspaceRoot, ["add", "."]);
|
||||
runGit(workspaceRoot, ["commit", "-m", "Initial perf workspace"]);
|
||||
}
|
||||
|
||||
function plusMs(baseTimeMs: number, offsetMs: number): string {
|
||||
return new Date(baseTimeMs + offsetMs).toISOString();
|
||||
}
|
||||
|
||||
function makeCommandId(prefix: string, threadId: string, turnIndex: number): CommandId {
|
||||
return CommandId.makeUnsafe(`${prefix}:${threadId}:${turnIndex.toString().padStart(4, "0")}`);
|
||||
}
|
||||
|
||||
function buildProjectEvent(
|
||||
project: PerfProjectScenario,
|
||||
workspaceRoot: string,
|
||||
createdAt: string,
|
||||
): Omit<OrchestrationEvent, "sequence"> {
|
||||
return {
|
||||
type: "project.created",
|
||||
eventId: EventId.makeUnsafe(`perf-project-created:${String(project.id)}`),
|
||||
aggregateKind: "project",
|
||||
aggregateId: project.id,
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot,
|
||||
defaultModelSelection: project.defaultModelSelection,
|
||||
scripts: [],
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildThreadCreatedEvent(
|
||||
thread: PerfSeedThreadScenario,
|
||||
project: PerfProjectScenario,
|
||||
createdAt: string,
|
||||
): Omit<OrchestrationEvent, "sequence"> {
|
||||
return {
|
||||
type: "thread.created",
|
||||
eventId: EventId.makeUnsafe(`perf-thread-created:${String(thread.id)}`),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: createdAt,
|
||||
commandId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
projectId: thread.projectId,
|
||||
title: thread.title,
|
||||
modelSelection: project.defaultModelSelection,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildUserMessageText(thread: PerfSeedThreadScenario, turnIndex: number): string {
|
||||
const base = `${thread.title} request ${turnIndex}: review the current workspace state and explain the next change.`;
|
||||
if (turnIndex % 11 === 0) {
|
||||
return `${base}\n\nFocus on virtualization, batching, and cross-thread navigation latency.`;
|
||||
}
|
||||
if (turnIndex % 7 === 0) {
|
||||
return `${base}\n\nSummarize CPU-sensitive paths and any websocket burst handling concerns.`;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
function buildAssistantMessageText(
|
||||
thread: PerfSeedThreadScenario,
|
||||
turnIndex: number,
|
||||
assistantMessageIndex: number,
|
||||
assistantMessageCount: number,
|
||||
): string {
|
||||
const phaseLabel =
|
||||
assistantMessageIndex === 1
|
||||
? "Opening"
|
||||
: assistantMessageIndex === assistantMessageCount
|
||||
? "Settled"
|
||||
: assistantMessageIndex % 5 === 0
|
||||
? "Checkpoint"
|
||||
: "Loop";
|
||||
const focusTopics = [
|
||||
"checked the visible timeline window and sidebar ordering",
|
||||
"trimmed redundant projection work before the next render pass",
|
||||
"reviewed websocket fan-out and message grouping pressure",
|
||||
"verified checkpoint rows stay bounded while hidden threads move",
|
||||
"kept the active route stable while background threads kept streaming",
|
||||
];
|
||||
const topic = focusTopics[(turnIndex + assistantMessageIndex) % focusTopics.length]!;
|
||||
const threadBias =
|
||||
thread.category === "heavy"
|
||||
? "The thread is still dense enough to stress virtualization."
|
||||
: thread.category === "burst"
|
||||
? "This pass is still carrying live burst pressure."
|
||||
: "Background churn is staying active without stealing focus.";
|
||||
|
||||
return `${thread.title} ${phaseLabel.toLowerCase()} ${assistantMessageIndex}/${assistantMessageCount} for turn ${turnIndex}: ${topic}. ${threadBias}`;
|
||||
}
|
||||
|
||||
function buildProposedPlanMarkdown(thread: PerfSeedThreadScenario, turnIndex: number): string {
|
||||
return [
|
||||
`## ${thread.title} plan ${turnIndex}`,
|
||||
"",
|
||||
"1. Measure the current thread switch path against a stable local budget.",
|
||||
"2. Reduce avoidable render churn in the visible timeline window.",
|
||||
"3. Validate websocket burst handling with real runtime events before tightening thresholds.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function buildCheckpointFiles(
|
||||
thread: PerfSeedThreadScenario,
|
||||
threadOrdinal: number,
|
||||
turnIndex: number,
|
||||
): ReadonlyArray<{
|
||||
readonly path: string;
|
||||
readonly kind: string;
|
||||
readonly additions: number;
|
||||
readonly deletions: number;
|
||||
}> {
|
||||
const nestedPathTemplates = [
|
||||
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "TimelineVirtualizer.tsx"],
|
||||
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "ThreadSummaryPane.tsx"],
|
||||
["apps", "web", "src", "hooks", `thread-${threadOrdinal + 1}`, "useThreadViewport.ts"],
|
||||
["apps", "web", "src", "stores", `thread-${threadOrdinal + 1}`, "timelineStore.ts"],
|
||||
[
|
||||
"apps",
|
||||
"server",
|
||||
"src",
|
||||
"orchestration",
|
||||
`thread-${threadOrdinal + 1}`,
|
||||
"projectionPipeline.ts",
|
||||
],
|
||||
["apps", "server", "src", "provider", `thread-${threadOrdinal + 1}`, "runtimeBuffer.ts"],
|
||||
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "fixtureBuilders.ts"],
|
||||
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "scenarioCatalog.ts"],
|
||||
["packages", "contracts", "src", "orchestration", `thread-${threadOrdinal + 1}`, "schemas.ts"],
|
||||
["docs", "perf", `thread-${threadOrdinal + 1}`, "notes", "regression-findings.md"],
|
||||
["scripts", "perf", `thread-${threadOrdinal + 1}`, "capture-profile.ts"],
|
||||
["test", "perf", "fixtures", `thread-${threadOrdinal + 1}`, "workspace-state.json"],
|
||||
] as const;
|
||||
const fileCount = thread.category === "heavy" ? 12 + (turnIndex % 7) : 7 + (turnIndex % 4);
|
||||
|
||||
return Array.from({ length: fileCount }, (_, fileIndex) => {
|
||||
const template = nestedPathTemplates[fileIndex % nestedPathTemplates.length]!;
|
||||
const variant = Math.floor(fileIndex / nestedPathTemplates.length);
|
||||
const baseSegments = [...template];
|
||||
const fileName = baseSegments.pop()!;
|
||||
const variantFileName =
|
||||
variant === 0
|
||||
? fileName
|
||||
: fileName.replace(/(\.[^.]*)$/, `-${(variant + 1).toString().padStart(2, "0")}$1`);
|
||||
const path = [...baseSegments, variantFileName].join("/");
|
||||
const kind =
|
||||
fileIndex % 9 === 0
|
||||
? "deleted"
|
||||
: fileIndex % 5 === 0
|
||||
? "added"
|
||||
: fileIndex % 4 === 0
|
||||
? "renamed"
|
||||
: "modified";
|
||||
|
||||
return {
|
||||
path,
|
||||
kind,
|
||||
additions: kind === "deleted" ? 0 : 4 + ((turnIndex + fileIndex) % 11),
|
||||
deletions: kind === "added" ? 0 : 1 + ((threadOrdinal + fileIndex + turnIndex) % 6),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildThreadTurnEvents(
|
||||
thread: PerfSeedThreadScenario,
|
||||
threadOrdinal: number,
|
||||
projectStartMs: number,
|
||||
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
|
||||
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
const threadStartMs = projectStartMs + threadOrdinal * 60_000;
|
||||
const assistantMessageCountPlan = buildPerfAssistantMessageCountPlan(thread);
|
||||
|
||||
for (let turnIndex = 1; turnIndex <= thread.turnCount; turnIndex += 1) {
|
||||
const turnId = perfTurnIdForThread(thread, turnIndex);
|
||||
const userMessageId = perfMessageIdForThread(thread, "user", turnIndex, 1);
|
||||
const assistantMessageCount = assistantMessageCountPlan[turnIndex - 1] ?? 1;
|
||||
const turnBaseMs = threadStartMs + turnIndex * 1_000;
|
||||
const userOccurredAt = plusMs(turnBaseMs, 0);
|
||||
const activityAssistantIndex =
|
||||
thread.activityStride !== null && turnIndex % thread.activityStride === 0
|
||||
? Math.max(2, Math.floor(assistantMessageCount * 0.35))
|
||||
: null;
|
||||
const planAssistantIndex =
|
||||
thread.planStride !== null && turnIndex % thread.planStride === 0
|
||||
? Math.max(2, Math.floor(assistantMessageCount * 0.7))
|
||||
: null;
|
||||
let lastAssistantMessageId = perfMessageIdForThread(
|
||||
thread,
|
||||
"assistant",
|
||||
turnIndex,
|
||||
assistantMessageCount,
|
||||
);
|
||||
let turnEventOffset = 0;
|
||||
const nextEventId = (prefix: string) =>
|
||||
perfEventId(prefix, thread.id, turnIndex * 100 + turnEventOffset++);
|
||||
|
||||
events.push({
|
||||
type: "thread.message-sent",
|
||||
eventId: nextEventId("perf-user-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: userOccurredAt,
|
||||
commandId: makeCommandId("perf-user-message", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
messageId: userMessageId,
|
||||
role: "user",
|
||||
text: buildUserMessageText(thread, turnIndex),
|
||||
attachments: [],
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: userOccurredAt,
|
||||
updatedAt: userOccurredAt,
|
||||
},
|
||||
});
|
||||
|
||||
for (
|
||||
let assistantMessageIndex = 1;
|
||||
assistantMessageIndex <= assistantMessageCount;
|
||||
assistantMessageIndex += 1
|
||||
) {
|
||||
const assistantOccurredAt = plusMs(turnBaseMs, 120 + assistantMessageIndex * 40);
|
||||
const assistantMessageId = perfMessageIdForThread(
|
||||
thread,
|
||||
"assistant",
|
||||
turnIndex,
|
||||
assistantMessageIndex,
|
||||
);
|
||||
lastAssistantMessageId = assistantMessageId;
|
||||
|
||||
events.push({
|
||||
type: "thread.message-sent",
|
||||
eventId: nextEventId("perf-assistant-message"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: assistantOccurredAt,
|
||||
commandId: makeCommandId("perf-assistant-message", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
messageId: assistantMessageId,
|
||||
role: "assistant",
|
||||
text: buildAssistantMessageText(
|
||||
thread,
|
||||
turnIndex,
|
||||
assistantMessageIndex,
|
||||
assistantMessageCount,
|
||||
),
|
||||
attachments: [],
|
||||
turnId,
|
||||
streaming: false,
|
||||
createdAt: assistantOccurredAt,
|
||||
updatedAt: assistantOccurredAt,
|
||||
},
|
||||
});
|
||||
|
||||
if (activityAssistantIndex === assistantMessageIndex) {
|
||||
const activityOccurredAt = plusMs(turnBaseMs, 132 + assistantMessageIndex * 40);
|
||||
events.push({
|
||||
type: "thread.activity-appended",
|
||||
eventId: nextEventId("perf-activity"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: activityOccurredAt,
|
||||
commandId: makeCommandId("perf-activity", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
activity: {
|
||||
id: perfEventId("perf-activity-row", thread.id, turnIndex),
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: `Synthetic command batch ${turnIndex}.${assistantMessageIndex}`,
|
||||
payload: {
|
||||
command: "perf-simulated",
|
||||
batch: turnIndex,
|
||||
loop: assistantMessageIndex,
|
||||
threadCategory: thread.category,
|
||||
},
|
||||
turnId,
|
||||
createdAt: activityOccurredAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (planAssistantIndex === assistantMessageIndex) {
|
||||
const planOccurredAt = plusMs(turnBaseMs, 140 + assistantMessageIndex * 40);
|
||||
events.push({
|
||||
type: "thread.proposed-plan-upserted",
|
||||
eventId: nextEventId("perf-plan"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: planOccurredAt,
|
||||
commandId: makeCommandId("perf-plan", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
proposedPlan: {
|
||||
id: `perf-plan:${String(thread.id)}:${turnIndex.toString().padStart(4, "0")}`,
|
||||
turnId,
|
||||
planMarkdown: buildProposedPlanMarkdown(thread, turnIndex),
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: planOccurredAt,
|
||||
updatedAt: planOccurredAt,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (thread.diffStride !== null && turnIndex % thread.diffStride === 0) {
|
||||
const diffOccurredAt = plusMs(turnBaseMs, 180 + assistantMessageCount * 40);
|
||||
events.push({
|
||||
type: "thread.turn-diff-completed",
|
||||
eventId: nextEventId("perf-diff"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: thread.id,
|
||||
occurredAt: diffOccurredAt,
|
||||
commandId: makeCommandId("perf-diff", String(thread.id), turnIndex),
|
||||
causationEventId: null,
|
||||
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
checkpointTurnCount: turnIndex,
|
||||
checkpointRef: CheckpointRef.makeUnsafe(
|
||||
`refs/perf/${String(thread.id)}/${turnIndex.toString().padStart(4, "0")}`,
|
||||
),
|
||||
status: "ready",
|
||||
files: buildCheckpointFiles(thread, threadOrdinal, turnIndex),
|
||||
assistantMessageId: lastAssistantMessageId,
|
||||
completedAt: diffOccurredAt,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
function buildScenarioEvents(
|
||||
scenario: PerfSeedScenario,
|
||||
workspaceRootsByProjectId: ReadonlyMap<ProjectId, string>,
|
||||
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
|
||||
const projectStartMs = Date.parse("2026-03-01T12:00:00.000Z");
|
||||
const threadsByProjectId = new Map<ProjectId, PerfSeedThreadScenario[]>();
|
||||
for (const thread of scenario.threads) {
|
||||
const existing = threadsByProjectId.get(thread.projectId) ?? [];
|
||||
existing.push(thread);
|
||||
threadsByProjectId.set(thread.projectId, existing);
|
||||
}
|
||||
|
||||
let globalThreadOrdinal = 0;
|
||||
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
|
||||
|
||||
for (const [projectOrdinal, project] of scenario.projects.entries()) {
|
||||
const projectWorkspaceRoot = workspaceRootsByProjectId.get(project.id);
|
||||
if (!projectWorkspaceRoot) {
|
||||
throw new Error(`Missing workspace root for perf project '${String(project.id)}'.`);
|
||||
}
|
||||
const projectBaseMs = projectStartMs + projectOrdinal * 6 * 60_000;
|
||||
const projectCreatedAt = plusMs(projectBaseMs, 0);
|
||||
const projectThreads = threadsByProjectId.get(project.id) ?? [];
|
||||
events.push(buildProjectEvent(project, projectWorkspaceRoot, projectCreatedAt));
|
||||
|
||||
for (const [threadOrdinalWithinProject, thread] of projectThreads.entries()) {
|
||||
const threadCreatedAt = plusMs(projectBaseMs, threadOrdinalWithinProject * 45_000 + 50);
|
||||
const threadEvents = buildThreadTurnEvents(thread, globalThreadOrdinal, projectBaseMs);
|
||||
globalThreadOrdinal += 1;
|
||||
events.push(buildThreadCreatedEvent(thread, project, threadCreatedAt), ...threadEvents);
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
async function createTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string> {
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const baseDir = await mkdtemp(join(tmpdir(), `t3-perf-template-${scenarioId}-`));
|
||||
const primaryProject = scenario.projects[0];
|
||||
if (!primaryProject) {
|
||||
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
|
||||
}
|
||||
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
|
||||
const workspaceRootsByProjectId = new Map<ProjectId, string>(
|
||||
scenario.projects.map((project) => [project.id, join(baseDir, project.workspaceDirectoryName)]),
|
||||
);
|
||||
|
||||
await Promise.all(
|
||||
scenario.projects.map((project) =>
|
||||
initializeGitWorkspace(join(baseDir, project.workspaceDirectoryName)),
|
||||
),
|
||||
);
|
||||
|
||||
const seedLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(OrchestrationProjectionPipelineLive),
|
||||
Layer.provideMerge(OrchestrationEventStoreLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(seedLayer);
|
||||
|
||||
const snapshot = await runtime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
enableAssistantStreaming: scenario.id === "burst_base",
|
||||
});
|
||||
|
||||
for (const event of buildScenarioEvents(scenario, workspaceRootsByProjectId)) {
|
||||
const storedEvent = yield* eventStore.append(event);
|
||||
yield* projectionPipeline.projectEvent(storedEvent);
|
||||
}
|
||||
|
||||
return yield* snapshotQuery.getSnapshot();
|
||||
}),
|
||||
);
|
||||
|
||||
const manifestPath = join(baseDir, "perf-seed-manifest.json");
|
||||
await writeFile(
|
||||
manifestPath,
|
||||
`${JSON.stringify(
|
||||
{
|
||||
scenarioId,
|
||||
workspaceRoot,
|
||||
snapshotSequence: snapshot.snapshotSequence,
|
||||
projectCount: snapshot.projects.length,
|
||||
threadCount: snapshot.threads.length,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`,
|
||||
"utf8",
|
||||
);
|
||||
|
||||
await runtime.dispose();
|
||||
return baseDir;
|
||||
}
|
||||
|
||||
async function getTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string> {
|
||||
const existing = templateDirPromises.get(scenarioId);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const created = createTemplateDir(scenarioId);
|
||||
templateDirPromises.set(scenarioId, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
export async function seedPerfState(scenarioId: PerfSeedScenarioId): Promise<PerfSeededState> {
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const templateDir = await getTemplateDir(scenarioId);
|
||||
const runParentDir = await mkdtemp(join(tmpdir(), `t3-perf-run-${scenarioId}-`));
|
||||
const baseDir = join(runParentDir, "base");
|
||||
await cp(templateDir, baseDir, { recursive: true, force: true });
|
||||
const primaryProject = scenario.projects[0];
|
||||
if (!primaryProject) {
|
||||
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
|
||||
}
|
||||
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
|
||||
|
||||
const snapshotLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtime = ManagedRuntime.make(snapshotLayer);
|
||||
const snapshot = await runtime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const snapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
return yield* snapshotQuery.getSnapshot();
|
||||
}),
|
||||
);
|
||||
await runtime.dispose();
|
||||
|
||||
return {
|
||||
scenarioId,
|
||||
runParentDir,
|
||||
baseDir,
|
||||
workspaceRoot,
|
||||
snapshot,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,920 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { performance } from "node:perf_hooks";
|
||||
|
||||
import {
|
||||
type ClientOrchestrationCommand,
|
||||
CommandId,
|
||||
MessageId,
|
||||
type ModelSelection,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
type OrchestrationEvent,
|
||||
type ProjectId,
|
||||
type TerminalEvent,
|
||||
ThreadId,
|
||||
type ThreadId as ThreadIdType,
|
||||
WS_METHODS,
|
||||
} from "@t3tools/contracts";
|
||||
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
type ServerCommandLatencyMeasurement,
|
||||
startServerPerfHarness,
|
||||
summarizeCommandLatencyMeasurements,
|
||||
summarizeRpcLatencySeries,
|
||||
type ServerPerfHarness,
|
||||
type ServerRpcLatencySeries,
|
||||
} from "./serverPerfHarness.ts";
|
||||
import type { PerfLatencySample } from "@t3tools/shared/perf/artifact";
|
||||
|
||||
const CONTROL_PLANE_SAMPLE_COUNT = 4;
|
||||
const GIT_RPC_SAMPLE_COUNT = 6;
|
||||
const STREAM_THREAD_COUNT = 5;
|
||||
const SPAM_THREAD_COUNT = 8;
|
||||
const TERMINAL_SESSION_COUNT = 3;
|
||||
const TERMINAL_OUTPUT_LINE_COUNT = 260;
|
||||
const TERMINAL_OUTPUT_SLEEP_SECONDS = 0.04;
|
||||
const GIT_BRANCH_COUNT = 240;
|
||||
const GIT_UNTRACKED_FILE_COUNT = 160;
|
||||
const DEFAULT_WAIT_TIMEOUT_MS = 45_000;
|
||||
|
||||
interface SubscriptionCleanup {
|
||||
readonly dispose: () => void;
|
||||
}
|
||||
|
||||
interface EventWaiter<TValue, TResult> {
|
||||
readonly description: string;
|
||||
readonly select: (values: ReadonlyArray<TValue>) => TResult | null;
|
||||
readonly resolve: (value: TResult) => void;
|
||||
readonly reject: (error: Error) => void;
|
||||
readonly timer: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
class BufferedEventFeed<TValue> implements SubscriptionCleanup {
|
||||
private readonly values: TValue[] = [];
|
||||
private readonly waiters = new Set<EventWaiter<TValue, unknown>>();
|
||||
|
||||
push(value: TValue) {
|
||||
this.values.push(value);
|
||||
for (const waiter of this.waiters) {
|
||||
const match = waiter.select(this.values);
|
||||
if (match === null) {
|
||||
continue;
|
||||
}
|
||||
clearTimeout(waiter.timer);
|
||||
this.waiters.delete(waiter);
|
||||
waiter.resolve(match);
|
||||
}
|
||||
}
|
||||
|
||||
waitFor<TResult>(
|
||||
description: string,
|
||||
select: (values: ReadonlyArray<TValue>) => TResult | null,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<TResult> {
|
||||
const immediateMatch = select(this.values);
|
||||
if (immediateMatch !== null) {
|
||||
return Promise.resolve(immediateMatch);
|
||||
}
|
||||
|
||||
return new Promise<TResult>((resolve, reject) => {
|
||||
const waiter: EventWaiter<TValue, TResult> = {
|
||||
description,
|
||||
select,
|
||||
resolve,
|
||||
reject,
|
||||
timer: setTimeout(() => {
|
||||
this.waiters.delete(waiter as EventWaiter<TValue, unknown>);
|
||||
reject(new Error(`Timed out waiting for ${description} after ${timeoutMs}ms.`));
|
||||
}, timeoutMs),
|
||||
};
|
||||
this.waiters.add(waiter as EventWaiter<TValue, unknown>);
|
||||
});
|
||||
}
|
||||
|
||||
waitForEvent(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<TValue> {
|
||||
return this.waitFor(description, (values) => values.find(predicate) ?? null, timeoutMs);
|
||||
}
|
||||
|
||||
waitForCount(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
count: number,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<ReadonlyArray<TValue>> {
|
||||
return this.waitFor(
|
||||
description,
|
||||
(values) => {
|
||||
const matches = values.filter(predicate);
|
||||
return matches.length >= count ? matches.slice(0, count) : null;
|
||||
},
|
||||
timeoutMs,
|
||||
);
|
||||
}
|
||||
|
||||
waitForDistinct<TKey extends string | number>(
|
||||
description: string,
|
||||
predicate: (value: TValue) => boolean,
|
||||
selectKey: (value: TValue) => TKey,
|
||||
count: number,
|
||||
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
|
||||
): Promise<ReadonlyArray<TValue>> {
|
||||
return this.waitFor(
|
||||
description,
|
||||
(values) => {
|
||||
const distinctMatches = new Map<TKey, TValue>();
|
||||
for (const value of values) {
|
||||
if (!predicate(value)) {
|
||||
continue;
|
||||
}
|
||||
const key = selectKey(value);
|
||||
if (!distinctMatches.has(key)) {
|
||||
distinctMatches.set(key, value);
|
||||
}
|
||||
}
|
||||
const matches = [...distinctMatches.values()];
|
||||
return matches.length >= count ? matches : null;
|
||||
},
|
||||
timeoutMs,
|
||||
);
|
||||
}
|
||||
|
||||
dispose() {
|
||||
for (const waiter of this.waiters) {
|
||||
clearTimeout(waiter.timer);
|
||||
waiter.reject(new Error(`Buffered feed disposed while waiting for ${waiter.description}.`));
|
||||
}
|
||||
this.waiters.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function sleep(delayMs: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, delayMs));
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
execFileSync("git", args, {
|
||||
cwd,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
encoding: "utf8",
|
||||
});
|
||||
}
|
||||
|
||||
function makeControlThreadId(label: string): ThreadIdType {
|
||||
return ThreadId.makeUnsafe(`perf-control-${label}-${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
function makeCommandId(label: string) {
|
||||
return CommandId.makeUnsafe(`perf-command:${label}:${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
function makeMessageId(label: string) {
|
||||
return MessageId.makeUnsafe(`perf-message:${label}:${crypto.randomUUID()}`);
|
||||
}
|
||||
|
||||
async function dispatchCommand(harness: ServerPerfHarness, command: ClientOrchestrationCommand) {
|
||||
return await harness.rpc.request((client) =>
|
||||
client[ORCHESTRATION_WS_METHODS.dispatchCommand](command),
|
||||
);
|
||||
}
|
||||
|
||||
async function measureCommandLatency(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly command: ClientOrchestrationCommand;
|
||||
readonly expectedEventType: OrchestrationEvent["type"];
|
||||
readonly loadProfile: string;
|
||||
readonly timeoutMs?: number;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}): Promise<ServerCommandLatencyMeasurement> {
|
||||
const startedAt = nowIso();
|
||||
const startedAtMs = performance.now();
|
||||
const result = await dispatchCommand(input.harness, input.command);
|
||||
const ackAtMs = performance.now();
|
||||
const event = await input.orchestrationEvents.waitForEvent(
|
||||
`${input.expectedEventType} for ${input.command.type}`,
|
||||
(candidate) =>
|
||||
candidate.type === input.expectedEventType &&
|
||||
String(candidate.commandId) === String(input.command.commandId),
|
||||
input.timeoutMs,
|
||||
);
|
||||
const eventAtMs = performance.now();
|
||||
|
||||
return {
|
||||
commandType: input.command.type,
|
||||
loadProfile: input.loadProfile,
|
||||
startedAt,
|
||||
dispatchToAckMs: ackAtMs - startedAtMs,
|
||||
dispatchToEventMs: eventAtMs - startedAtMs,
|
||||
ackToEventMs: eventAtMs - ackAtMs,
|
||||
resultSequence: result.sequence,
|
||||
eventSequence: event.sequence,
|
||||
...(input.metadata ? { metadata: input.metadata } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function createSupportThread(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly label: string;
|
||||
}): Promise<ThreadIdType> {
|
||||
const threadId = makeControlThreadId(`load-${input.label}`);
|
||||
const command = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`load-thread-create-${input.label}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf Load ${input.label}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
await dispatchCommand(input.harness, command);
|
||||
await input.orchestrationEvents.waitForEvent(
|
||||
`thread.created for load support thread ${input.label}`,
|
||||
(event) => event.type === "thread.created" && event.payload.threadId === threadId,
|
||||
);
|
||||
return threadId;
|
||||
}
|
||||
|
||||
async function captureCreateArchiveSamples(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly loadProfile: string;
|
||||
readonly sampleCount: number;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
}): Promise<ReadonlyArray<ServerCommandLatencyMeasurement>> {
|
||||
const samples: ServerCommandLatencyMeasurement[] = [];
|
||||
|
||||
for (let sampleIndex = 0; sampleIndex < input.sampleCount; sampleIndex += 1) {
|
||||
const threadId = makeControlThreadId(`${input.loadProfile}-${sampleIndex + 1}`);
|
||||
const createCommand = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`thread-create-${input.loadProfile}-${sampleIndex + 1}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf ${input.loadProfile} ${sampleIndex + 1}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
samples.push(
|
||||
await measureCommandLatency({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
command: createCommand,
|
||||
expectedEventType: "thread.created",
|
||||
loadProfile: input.loadProfile,
|
||||
metadata: {
|
||||
sampleIndex: sampleIndex + 1,
|
||||
threadId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const archiveCommand = {
|
||||
type: "thread.archive",
|
||||
commandId: makeCommandId(`thread-archive-${input.loadProfile}-${sampleIndex + 1}`),
|
||||
threadId,
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
|
||||
samples.push(
|
||||
await measureCommandLatency({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
command: archiveCommand,
|
||||
expectedEventType: "thread.archived",
|
||||
loadProfile: input.loadProfile,
|
||||
metadata: {
|
||||
sampleIndex: sampleIndex + 1,
|
||||
threadId,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return samples;
|
||||
}
|
||||
|
||||
async function ensureStreamingThreads(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly count: number;
|
||||
}): Promise<ReadonlyArray<ThreadIdType>> {
|
||||
const threadIds: ThreadIdType[] = [
|
||||
PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
PERF_CATALOG_IDS.burstBase.fillerThreadId,
|
||||
];
|
||||
|
||||
while (threadIds.length < input.count) {
|
||||
threadIds.push(
|
||||
await createSupportThread({
|
||||
harness: input.harness,
|
||||
orchestrationEvents: input.orchestrationEvents,
|
||||
projectId: input.projectId,
|
||||
modelSelection: input.modelSelection,
|
||||
label: `stream-${threadIds.length + 1}`,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return threadIds;
|
||||
}
|
||||
|
||||
async function startAssistantStreamingLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
readonly label: string;
|
||||
}): Promise<void> {
|
||||
await Promise.all(
|
||||
input.threadIds.map((threadId, index) =>
|
||||
dispatchCommand(input.harness, {
|
||||
type: "thread.turn.start",
|
||||
commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: makeMessageId(`${input.label}-turn-${index + 1}`),
|
||||
role: "user",
|
||||
text: `Perf load ${input.label} ${index + 1}`,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand),
|
||||
),
|
||||
);
|
||||
|
||||
const threadIds = new Set(input.threadIds.map(String));
|
||||
await input.orchestrationEvents.waitForDistinct(
|
||||
`assistant streaming output for ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.role === "assistant" &&
|
||||
event.payload.streaming &&
|
||||
threadIds.has(String(event.payload.threadId)),
|
||||
(event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""),
|
||||
input.threadIds.length,
|
||||
);
|
||||
}
|
||||
|
||||
async function startCreateTurnSpamLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
|
||||
readonly projectId: ProjectId;
|
||||
readonly modelSelection: ModelSelection;
|
||||
readonly count: number;
|
||||
readonly label: string;
|
||||
}): Promise<{
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
readonly done: Promise<ReadonlyArray<ThreadIdType>>;
|
||||
}> {
|
||||
const threadIds = Array.from({ length: input.count }, (_, index) =>
|
||||
makeControlThreadId(`${input.label}-${index + 1}`),
|
||||
);
|
||||
const threadIdStrings = new Set(threadIds.map(String));
|
||||
|
||||
const done = Promise.all(
|
||||
threadIds.map(async (threadId, index) => {
|
||||
const createCommand = {
|
||||
type: "thread.create",
|
||||
commandId: makeCommandId(`${input.label}-create-${index + 1}`),
|
||||
threadId,
|
||||
projectId: input.projectId,
|
||||
title: `Perf Spam ${index + 1}`,
|
||||
modelSelection: input.modelSelection,
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand;
|
||||
await dispatchCommand(input.harness, createCommand);
|
||||
await input.orchestrationEvents.waitForEvent(
|
||||
`thread.created for ${input.label}-${index + 1}`,
|
||||
(event) => event.type === "thread.created" && event.payload.threadId === threadId,
|
||||
);
|
||||
await dispatchCommand(input.harness, {
|
||||
type: "thread.turn.start",
|
||||
commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`),
|
||||
threadId,
|
||||
message: {
|
||||
messageId: makeMessageId(`${input.label}-turn-${index + 1}`),
|
||||
role: "user",
|
||||
text: `Perf spam ${input.label} ${index + 1}`,
|
||||
attachments: [],
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
createdAt: nowIso(),
|
||||
} as const satisfies ClientOrchestrationCommand);
|
||||
return threadId;
|
||||
}),
|
||||
);
|
||||
|
||||
await input.orchestrationEvents.waitForCount(
|
||||
`thread.create spam ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.created" && threadIdStrings.has(String(event.payload.threadId)),
|
||||
Math.min(4, input.count),
|
||||
);
|
||||
await input.orchestrationEvents.waitForDistinct(
|
||||
`assistant spam output ${input.label}`,
|
||||
(event) =>
|
||||
event.type === "thread.message-sent" &&
|
||||
event.payload.role === "assistant" &&
|
||||
event.payload.streaming &&
|
||||
threadIdStrings.has(String(event.payload.threadId)),
|
||||
(event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""),
|
||||
Math.min(4, input.count),
|
||||
);
|
||||
|
||||
return {
|
||||
threadIds,
|
||||
done,
|
||||
};
|
||||
}
|
||||
|
||||
async function startTerminalLoad(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly terminalEvents: BufferedEventFeed<TerminalEvent>;
|
||||
readonly workspaceRoot: string;
|
||||
readonly threadIds: ReadonlyArray<ThreadIdType>;
|
||||
}): Promise<ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>> {
|
||||
const sessions = await Promise.all(
|
||||
input.threadIds.slice(0, TERMINAL_SESSION_COUNT).map(async (threadId, index) => {
|
||||
const terminalId = `perf-${index + 1}`;
|
||||
await input.harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalOpen]({
|
||||
threadId,
|
||||
terminalId,
|
||||
cwd: input.workspaceRoot,
|
||||
cols: 120,
|
||||
rows: 32,
|
||||
}),
|
||||
);
|
||||
|
||||
const command = [
|
||||
"i=1",
|
||||
`while [ $i -le ${TERMINAL_OUTPUT_LINE_COUNT} ]`,
|
||||
"do",
|
||||
` printf 'perf-terminal-${index + 1}-%03d\\n' "$i"`,
|
||||
" i=$((i + 1))",
|
||||
` sleep ${TERMINAL_OUTPUT_SLEEP_SECONDS.toFixed(2)}`,
|
||||
"done",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
await input.harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalWrite]({
|
||||
threadId,
|
||||
terminalId,
|
||||
data: command,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
threadId,
|
||||
terminalId,
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
const terminalIds = new Set(sessions.map((session) => session.terminalId));
|
||||
await input.terminalEvents.waitForDistinct(
|
||||
"terminal output load",
|
||||
(event) => event.type === "output" && terminalIds.has(event.terminalId),
|
||||
(event) => event.terminalId,
|
||||
sessions.length,
|
||||
30_000,
|
||||
);
|
||||
|
||||
return sessions;
|
||||
}
|
||||
|
||||
async function closeTerminalLoad(
|
||||
harness: ServerPerfHarness,
|
||||
sessions: ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>,
|
||||
): Promise<void> {
|
||||
await Promise.all(
|
||||
sessions.map((session) =>
|
||||
harness.rpc.request((client) =>
|
||||
client[WS_METHODS.terminalClose]({
|
||||
threadId: session.threadId,
|
||||
terminalId: session.terminalId,
|
||||
deleteHistory: true,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async function seedGitPressure(workspaceRoot: string): Promise<void> {
|
||||
const untrackedDir = join(workspaceRoot, "perf-git-pressure");
|
||||
await mkdir(untrackedDir, { recursive: true });
|
||||
await Promise.all(
|
||||
Array.from({ length: GIT_UNTRACKED_FILE_COUNT }, (_, index) =>
|
||||
writeFile(
|
||||
join(untrackedDir, `untracked-${(index + 1).toString().padStart(3, "0")}.ts`),
|
||||
`export const perfFile${index + 1} = ${index + 1};\n`,
|
||||
"utf8",
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
for (let index = 0; index < GIT_BRANCH_COUNT; index += 1) {
|
||||
runGit(workspaceRoot, ["branch", `perf/latency-${(index + 1).toString().padStart(4, "0")}`]);
|
||||
}
|
||||
}
|
||||
|
||||
async function measureRpcLatencySeries<TResult>(input: {
|
||||
readonly harness: ServerPerfHarness;
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly iterations: number;
|
||||
readonly execute: () => Promise<TResult>;
|
||||
}): Promise<ServerRpcLatencySeries> {
|
||||
const samples: PerfLatencySample[] = [];
|
||||
|
||||
for (let iteration = 0; iteration < input.iterations; iteration += 1) {
|
||||
const startedAt = nowIso();
|
||||
const startedAtMs = performance.now();
|
||||
await input.execute();
|
||||
const endedAtMs = performance.now();
|
||||
samples.push({
|
||||
name: `${input.name}-${iteration + 1}`,
|
||||
durationMs: endedAtMs - startedAtMs,
|
||||
startedAt,
|
||||
endedAt: nowIso(),
|
||||
metadata: {
|
||||
iteration: iteration + 1,
|
||||
loadProfile: input.loadProfile,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
name: input.name,
|
||||
loadProfile: input.loadProfile,
|
||||
summary: summarizeRpcLatencySeries(samples),
|
||||
samples,
|
||||
};
|
||||
}
|
||||
|
||||
function groupCommandSeries(
|
||||
samples: ReadonlyArray<ServerCommandLatencyMeasurement>,
|
||||
loadProfile: string,
|
||||
) {
|
||||
const createSamples = samples.filter((sample) => sample.commandType === "thread.create");
|
||||
const archiveSamples = samples.filter((sample) => sample.commandType === "thread.archive");
|
||||
|
||||
return [
|
||||
{
|
||||
name: "thread.create",
|
||||
loadProfile,
|
||||
summary: summarizeCommandLatencyMeasurements(createSamples),
|
||||
samples: createSamples,
|
||||
},
|
||||
{
|
||||
name: "thread.archive",
|
||||
loadProfile,
|
||||
summary: summarizeCommandLatencyMeasurements(archiveSamples),
|
||||
samples: archiveSamples,
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
|
||||
describe("server perf latency", () => {
|
||||
const disposables: Array<SubscriptionCleanup> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const disposable of disposables.splice(0)) {
|
||||
disposable.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it("records idle and assistant-stream command latency at the websocket boundary", async () => {
|
||||
let harness: ServerPerfHarness | null = null;
|
||||
|
||||
try {
|
||||
harness = await startServerPerfHarness({
|
||||
suite: "server-latency-critical-commands",
|
||||
seedScenarioId: "burst_base",
|
||||
providerScenarioId: "parallel_assistant_stream",
|
||||
});
|
||||
const runStartedAt = nowIso();
|
||||
|
||||
const burstProject = harness.seededState.snapshot.projects.find(
|
||||
(project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId,
|
||||
);
|
||||
expect(burstProject).toBeTruthy();
|
||||
const modelSelection = burstProject!.defaultModelSelection;
|
||||
expect(modelSelection).toBeTruthy();
|
||||
|
||||
const orchestrationEvents = new BufferedEventFeed<OrchestrationEvent>();
|
||||
disposables.push(orchestrationEvents);
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
|
||||
(event) => orchestrationEvents.push(event),
|
||||
),
|
||||
});
|
||||
|
||||
await sleep(250);
|
||||
|
||||
const idleSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "idle",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
const streamingThreadIds = await ensureStreamingThreads({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: STREAM_THREAD_COUNT,
|
||||
});
|
||||
await startAssistantStreamingLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
threadIds: streamingThreadIds,
|
||||
label: "stream-control-plane",
|
||||
});
|
||||
|
||||
const streamingSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "assistant-stream-5x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
const spamLoad = await startCreateTurnSpamLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: SPAM_THREAD_COUNT,
|
||||
label: "create-turn-spam-8x",
|
||||
});
|
||||
const spamSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "create-turn-spam-8x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
await spamLoad.done;
|
||||
|
||||
const commandLatency = [
|
||||
...groupCommandSeries(idleSamples, "idle"),
|
||||
...groupCommandSeries(streamingSamples, "assistant-stream-5x"),
|
||||
...groupCommandSeries(spamSamples, "create-turn-spam-8x"),
|
||||
];
|
||||
const result = await harness.finishRun({
|
||||
artifactBasename: "control-plane-stream-baseline",
|
||||
artifact: {
|
||||
suite: "server-latency-critical-commands",
|
||||
scenarioId: "burst_base_control_plane_stream_baseline",
|
||||
startedAt: runStartedAt,
|
||||
completedAt: nowIso(),
|
||||
commandLatency,
|
||||
rpcLatency: [],
|
||||
metadata: {
|
||||
sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
streamingThreadCount: STREAM_THREAD_COUNT,
|
||||
spamThreadCount: SPAM_THREAD_COUNT,
|
||||
},
|
||||
},
|
||||
});
|
||||
harness = null;
|
||||
|
||||
expect(result.artifact.commandLatency).toHaveLength(6);
|
||||
for (const series of result.artifact.commandLatency) {
|
||||
expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT);
|
||||
expect(series.summary.dispatchToEventMs.p50Ms).not.toBeNull();
|
||||
expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
} finally {
|
||||
await harness?.dispose();
|
||||
}
|
||||
}, 180_000);
|
||||
|
||||
it("records command and git rpc latency under terminal and mixed server load", async () => {
|
||||
let harness: ServerPerfHarness | null = null;
|
||||
let terminalSessions: ReadonlyArray<{
|
||||
readonly threadId: ThreadIdType;
|
||||
readonly terminalId: string;
|
||||
}> = [];
|
||||
|
||||
try {
|
||||
harness = await startServerPerfHarness({
|
||||
suite: "server-latency-critical-commands",
|
||||
seedScenarioId: "burst_base",
|
||||
providerScenarioId: "parallel_assistant_stream",
|
||||
});
|
||||
const runStartedAt = nowIso();
|
||||
|
||||
const burstProject = harness.seededState.snapshot.projects.find(
|
||||
(project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId,
|
||||
);
|
||||
expect(burstProject).toBeTruthy();
|
||||
const modelSelection = burstProject!.defaultModelSelection;
|
||||
expect(modelSelection).toBeTruthy();
|
||||
|
||||
const orchestrationEvents = new BufferedEventFeed<OrchestrationEvent>();
|
||||
const terminalEvents = new BufferedEventFeed<TerminalEvent>();
|
||||
disposables.push(orchestrationEvents, terminalEvents);
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
|
||||
(event) => orchestrationEvents.push(event),
|
||||
),
|
||||
});
|
||||
disposables.push({
|
||||
dispose: harness.rpc.subscribe(
|
||||
(client) => client[WS_METHODS.subscribeTerminalEvents]({}),
|
||||
(event) => terminalEvents.push(event),
|
||||
),
|
||||
});
|
||||
|
||||
await sleep(250);
|
||||
await seedGitPressure(harness.seededState.workspaceRoot);
|
||||
|
||||
const gitLatencyIdle = await Promise.all([
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.status",
|
||||
loadProfile: "idle-repo-pressure",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitStatus]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.listBranches",
|
||||
loadProfile: "idle-repo-pressure",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitListBranches]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
const streamingThreadIds = await ensureStreamingThreads({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
count: STREAM_THREAD_COUNT,
|
||||
});
|
||||
|
||||
terminalSessions = await startTerminalLoad({
|
||||
harness,
|
||||
terminalEvents,
|
||||
workspaceRoot: harness.seededState.workspaceRoot,
|
||||
threadIds: streamingThreadIds,
|
||||
});
|
||||
|
||||
const terminalSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "terminal-output-3x",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
await sleep(6_500);
|
||||
await startAssistantStreamingLoad({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
threadIds: streamingThreadIds,
|
||||
label: "mixed-load",
|
||||
});
|
||||
await terminalEvents.waitForCount(
|
||||
"continued terminal output during mixed load",
|
||||
(event) =>
|
||||
event.type === "output" &&
|
||||
terminalSessions.some((session) => session.terminalId === event.terminalId),
|
||||
TERMINAL_SESSION_COUNT,
|
||||
30_000,
|
||||
);
|
||||
|
||||
const mixedSamples = await captureCreateArchiveSamples({
|
||||
harness,
|
||||
orchestrationEvents,
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
projectId: burstProject!.id,
|
||||
modelSelection: modelSelection!,
|
||||
});
|
||||
|
||||
const gitLatencyMixed = await Promise.all([
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.status",
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitStatus]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
measureRpcLatencySeries({
|
||||
harness,
|
||||
name: "git.listBranches",
|
||||
loadProfile: "mixed-stream-terminal-git",
|
||||
iterations: GIT_RPC_SAMPLE_COUNT,
|
||||
execute: () =>
|
||||
harness!.rpc.request((client) =>
|
||||
client[WS_METHODS.gitListBranches]({
|
||||
cwd: harness!.seededState.workspaceRoot,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
await closeTerminalLoad(harness, terminalSessions);
|
||||
terminalSessions = [];
|
||||
|
||||
const result = await harness.finishRun({
|
||||
artifactBasename: "terminal-mixed-git-baseline",
|
||||
artifact: {
|
||||
suite: "server-latency-critical-commands",
|
||||
scenarioId: "burst_base_terminal_mixed_git_baseline",
|
||||
startedAt: runStartedAt,
|
||||
completedAt: nowIso(),
|
||||
commandLatency: [
|
||||
...groupCommandSeries(terminalSamples, "terminal-output-3x"),
|
||||
...groupCommandSeries(mixedSamples, "mixed-stream-terminal-git"),
|
||||
],
|
||||
rpcLatency: [...gitLatencyIdle, ...gitLatencyMixed],
|
||||
metadata: {
|
||||
sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT,
|
||||
gitRpcSampleCount: GIT_RPC_SAMPLE_COUNT,
|
||||
branchCount: GIT_BRANCH_COUNT,
|
||||
untrackedFileCount: GIT_UNTRACKED_FILE_COUNT,
|
||||
terminalSessionCount: TERMINAL_SESSION_COUNT,
|
||||
},
|
||||
},
|
||||
});
|
||||
harness = null;
|
||||
|
||||
expect(result.artifact.commandLatency).toHaveLength(4);
|
||||
expect(result.artifact.rpcLatency).toHaveLength(4);
|
||||
for (const series of result.artifact.commandLatency) {
|
||||
expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT);
|
||||
expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
for (const series of result.artifact.rpcLatency) {
|
||||
expect(series.samples).toHaveLength(GIT_RPC_SAMPLE_COUNT);
|
||||
expect(series.summary.maxMs).toBeLessThan(30_000);
|
||||
}
|
||||
} finally {
|
||||
if (harness && terminalSessions.length > 0) {
|
||||
await closeTerminalLoad(harness, terminalSessions).catch(() => undefined);
|
||||
}
|
||||
await harness?.dispose();
|
||||
}
|
||||
}, 180_000);
|
||||
});
|
||||
@@ -0,0 +1,393 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { createServer } from "node:net";
|
||||
import { join, resolve } from "node:path";
|
||||
import { performance } from "node:perf_hooks";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import * as NodeSocket from "@effect/platform-node/NodeSocket";
|
||||
import {
|
||||
type OrchestrationEvent,
|
||||
type TerminalEvent,
|
||||
WS_METHODS,
|
||||
WsRpcGroup,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Effect,
|
||||
Exit,
|
||||
Layer,
|
||||
ManagedRuntime,
|
||||
Scope,
|
||||
Stream,
|
||||
type Scope as ScopeService,
|
||||
} from "effect";
|
||||
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
|
||||
import {
|
||||
summarizeLatencySamples,
|
||||
summarizeLatencyValues,
|
||||
type PerfLatencySample,
|
||||
type PerfLatencySummary,
|
||||
writeJsonArtifact,
|
||||
} from "@t3tools/shared/perf/artifact";
|
||||
import type {
|
||||
PerfProviderScenarioId,
|
||||
PerfSeedScenarioId,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { seedPerfState, type PerfSeededState } from "./seedPerfState.ts";
|
||||
|
||||
const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url));
|
||||
const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
|
||||
const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
|
||||
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
const AUTO_BOOTSTRAP_PROJECT_ENV = "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD";
|
||||
|
||||
const makeWsRpcClient = RpcClient.make(WsRpcGroup);
|
||||
type WsRpcClient =
|
||||
typeof makeWsRpcClient extends Effect.Effect<infer Client, any, any> ? Client : never;
|
||||
|
||||
export interface ServerCommandLatencyMeasurement {
|
||||
readonly commandType: string;
|
||||
readonly loadProfile: string;
|
||||
readonly startedAt: string;
|
||||
readonly dispatchToAckMs: number;
|
||||
readonly dispatchToEventMs: number;
|
||||
readonly ackToEventMs: number;
|
||||
readonly resultSequence: number;
|
||||
readonly eventSequence: number;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ServerCommandLatencySummary {
|
||||
readonly count: number;
|
||||
readonly dispatchToAckMs: PerfLatencySummary;
|
||||
readonly dispatchToEventMs: PerfLatencySummary;
|
||||
readonly ackToEventMs: PerfLatencySummary;
|
||||
}
|
||||
|
||||
export interface ServerCommandLatencySeries {
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly summary: ServerCommandLatencySummary;
|
||||
readonly samples: ReadonlyArray<ServerCommandLatencyMeasurement>;
|
||||
}
|
||||
|
||||
export interface ServerRpcLatencySeries {
|
||||
readonly name: string;
|
||||
readonly loadProfile: string;
|
||||
readonly summary: PerfLatencySummary;
|
||||
readonly samples: ReadonlyArray<PerfLatencySample>;
|
||||
}
|
||||
|
||||
export interface ServerPerfRunArtifact {
|
||||
readonly suite: string;
|
||||
readonly scenarioId: string;
|
||||
readonly startedAt: string;
|
||||
readonly completedAt: string;
|
||||
readonly commandLatency: ReadonlyArray<ServerCommandLatencySeries>;
|
||||
readonly rpcLatency: ReadonlyArray<ServerRpcLatencySeries>;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
interface StartServerPerfHarnessOptions {
|
||||
readonly suite: string;
|
||||
readonly seedScenarioId: PerfSeedScenarioId;
|
||||
readonly providerScenarioId?: PerfProviderScenarioId;
|
||||
}
|
||||
|
||||
interface FinishServerPerfRunOptions {
|
||||
readonly artifactBasename?: string;
|
||||
readonly artifact: ServerPerfRunArtifact;
|
||||
}
|
||||
|
||||
export interface ServerPerfHarness {
|
||||
readonly seededState: PerfSeededState;
|
||||
readonly wsUrl: string;
|
||||
readonly artifactDir: string;
|
||||
readonly rpc: PerfWsRpcClient;
|
||||
readonly finishRun: (options: FinishServerPerfRunOptions) => Promise<{
|
||||
readonly artifactPath: string;
|
||||
readonly artifact: ServerPerfRunArtifact;
|
||||
}>;
|
||||
readonly dispose: () => Promise<void>;
|
||||
}
|
||||
|
||||
const wsRpcProtocolLayer = (wsUrl: string) =>
|
||||
RpcClient.layerProtocolSocket().pipe(
|
||||
Layer.provide(NodeSocket.layerWebSocket(wsUrl)),
|
||||
Layer.provide(RpcSerialization.layerJson),
|
||||
);
|
||||
|
||||
async function pickFreePort(): Promise<number> {
|
||||
return await new Promise<number>((resolvePort, reject) => {
|
||||
const server = createServer();
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Unable to resolve a free localhost port."));
|
||||
return;
|
||||
}
|
||||
const { port } = address;
|
||||
server.close((closeError) => {
|
||||
if (closeError) {
|
||||
reject(closeError);
|
||||
return;
|
||||
}
|
||||
resolvePort(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function stopChildProcess(process: ChildProcess): Promise<void> {
|
||||
if (process.exitCode !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.kill("SIGTERM");
|
||||
const exited = await new Promise<boolean>((resolveExited) => {
|
||||
const timer = setTimeout(() => resolveExited(false), 5_000);
|
||||
process.once("exit", () => {
|
||||
clearTimeout(timer);
|
||||
resolveExited(true);
|
||||
});
|
||||
});
|
||||
|
||||
if (!exited && process.exitCode === null) {
|
||||
process.kill("SIGKILL");
|
||||
await new Promise<void>((resolveExited) => {
|
||||
process.once("exit", () => resolveExited());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureArtifactDir(suite: string, scenarioId: string): Promise<string> {
|
||||
const baseArtifactDir = resolve(
|
||||
process.env[PERF_ARTIFACT_DIR_ENV] ?? join(repoRoot, "artifacts/perf/server"),
|
||||
);
|
||||
const runId = `${suite}-${scenarioId}-${Date.now().toString()}`;
|
||||
const artifactDir = join(baseArtifactDir, runId);
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
async function writeServerLogs(
|
||||
artifactDir: string,
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
basename: string,
|
||||
): Promise<void> {
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(join(artifactDir, `${basename}.server.stdout.log`), stdout, "utf8"),
|
||||
writeFile(join(artifactDir, `${basename}.server.stderr.log`), stderr, "utf8"),
|
||||
]);
|
||||
}
|
||||
|
||||
function buildPerfServerEnv(
|
||||
baseEnv: NodeJS.ProcessEnv,
|
||||
providerScenarioId?: PerfProviderScenarioId,
|
||||
): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...baseEnv,
|
||||
[AUTO_BOOTSTRAP_PROJECT_ENV]: "false",
|
||||
};
|
||||
|
||||
if (!providerScenarioId) {
|
||||
delete env[PERF_PROVIDER_ENV];
|
||||
delete env[PERF_SCENARIO_ENV];
|
||||
return env;
|
||||
}
|
||||
|
||||
return {
|
||||
...env,
|
||||
[PERF_PROVIDER_ENV]: "1",
|
||||
[PERF_SCENARIO_ENV]: providerScenarioId,
|
||||
};
|
||||
}
|
||||
|
||||
export class PerfWsRpcClient {
|
||||
private readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
|
||||
private readonly clientScope: Scope.Closeable;
|
||||
private readonly clientPromise: Promise<WsRpcClient>;
|
||||
private disposed = false;
|
||||
|
||||
constructor(private readonly wsUrl: string) {
|
||||
this.runtime = ManagedRuntime.make(wsRpcProtocolLayer(wsUrl));
|
||||
this.clientScope = this.runtime.runSync(Scope.make());
|
||||
this.clientPromise = this.runtime.runPromise(Scope.provide(this.clientScope)(makeWsRpcClient));
|
||||
}
|
||||
|
||||
async request<TSuccess, TError>(
|
||||
execute: (client: WsRpcClient) => Effect.Effect<TSuccess, TError, never>,
|
||||
): Promise<TSuccess> {
|
||||
if (this.disposed) {
|
||||
throw new Error(`WebSocket RPC client disposed for ${this.wsUrl}`);
|
||||
}
|
||||
|
||||
const client = await this.clientPromise;
|
||||
return await this.runtime.runPromise(Effect.suspend(() => execute(client)));
|
||||
}
|
||||
|
||||
subscribe<TValue>(
|
||||
connect: (client: WsRpcClient) => Stream.Stream<TValue, Error, never>,
|
||||
listener: (value: TValue) => void,
|
||||
): () => void {
|
||||
if (this.disposed) {
|
||||
return () => undefined;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
const cancel = this.runtime.runCallback(
|
||||
Effect.promise(() => this.clientPromise).pipe(
|
||||
Effect.flatMap((client) =>
|
||||
Stream.runForEach(connect(client), (value) =>
|
||||
Effect.sync(() => {
|
||||
if (!active) {
|
||||
return;
|
||||
}
|
||||
listener(value);
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
cancel();
|
||||
};
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
if (this.disposed) {
|
||||
return;
|
||||
}
|
||||
this.disposed = true;
|
||||
await this.runtime.runPromise(Scope.close(this.clientScope, Exit.void));
|
||||
await this.runtime.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForRpcReady(wsUrl: string, process: ChildProcess): Promise<void> {
|
||||
const startedAtMs = performance.now();
|
||||
const timeoutMs = 45_000;
|
||||
|
||||
while (performance.now() - startedAtMs < timeoutMs) {
|
||||
if (process.exitCode !== null) {
|
||||
throw new Error(`Perf server exited early with code ${process.exitCode}.`);
|
||||
}
|
||||
|
||||
const client = new PerfWsRpcClient(wsUrl);
|
||||
try {
|
||||
await client.request((rpcClient) => rpcClient[WS_METHODS.serverGetSettings]({}));
|
||||
await client.dispose();
|
||||
return;
|
||||
} catch {
|
||||
await client.dispose().catch(() => undefined);
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 200));
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Timed out waiting for websocket readiness at ${wsUrl}.`);
|
||||
}
|
||||
|
||||
export function summarizeCommandLatencyMeasurements(
|
||||
samples: ReadonlyArray<ServerCommandLatencyMeasurement>,
|
||||
): ServerCommandLatencySummary {
|
||||
return {
|
||||
count: samples.length,
|
||||
dispatchToAckMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToAckMs)),
|
||||
dispatchToEventMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToEventMs)),
|
||||
ackToEventMs: summarizeLatencyValues(samples.map((sample) => sample.ackToEventMs)),
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeRpcLatencySeries(
|
||||
samples: ReadonlyArray<PerfLatencySample>,
|
||||
): PerfLatencySummary {
|
||||
return summarizeLatencySamples(samples);
|
||||
}
|
||||
|
||||
export async function startServerPerfHarness(
|
||||
options: StartServerPerfHarnessOptions,
|
||||
): Promise<ServerPerfHarness> {
|
||||
const seededState = await seedPerfState(options.seedScenarioId);
|
||||
const artifactDir = await ensureArtifactDir(options.suite, options.seedScenarioId);
|
||||
const port = await pickFreePort();
|
||||
const wsUrl = `ws://127.0.0.1:${port}/ws`;
|
||||
const env = buildPerfServerEnv(process.env, options.providerScenarioId);
|
||||
|
||||
let stdoutBuffer = "";
|
||||
let stderrBuffer = "";
|
||||
let finished = false;
|
||||
const serverProcess = spawn(
|
||||
"bun",
|
||||
[
|
||||
"run",
|
||||
"apps/server/src/bin.ts",
|
||||
"--mode",
|
||||
"web",
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
`${port}`,
|
||||
"--base-dir",
|
||||
seededState.baseDir,
|
||||
"--no-browser",
|
||||
],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
serverProcess.stdout?.on("data", (chunk) => {
|
||||
stdoutBuffer += chunk.toString();
|
||||
});
|
||||
serverProcess.stderr?.on("data", (chunk) => {
|
||||
stderrBuffer += chunk.toString();
|
||||
});
|
||||
|
||||
const cleanup = async () => {
|
||||
if (finished) {
|
||||
return;
|
||||
}
|
||||
finished = true;
|
||||
await stopChildProcess(serverProcess);
|
||||
await rm(seededState.runParentDir, { recursive: true, force: true });
|
||||
};
|
||||
|
||||
try {
|
||||
await waitForRpcReady(wsUrl, serverProcess);
|
||||
const rpc = new PerfWsRpcClient(wsUrl);
|
||||
|
||||
return {
|
||||
seededState,
|
||||
wsUrl,
|
||||
artifactDir,
|
||||
rpc,
|
||||
finishRun: async ({ artifactBasename, artifact }) => {
|
||||
const basename = artifactBasename ?? `${artifact.suite}-${artifact.scenarioId}`;
|
||||
await rpc.dispose();
|
||||
await cleanup();
|
||||
await writeServerLogs(artifactDir, stdoutBuffer, stderrBuffer, basename);
|
||||
const artifactPath = join(artifactDir, `${basename}.json`);
|
||||
await writeJsonArtifact(artifactPath, artifact);
|
||||
return {
|
||||
artifactPath,
|
||||
artifact,
|
||||
};
|
||||
},
|
||||
dispose: async () => {
|
||||
await rpc.dispose().catch(() => undefined);
|
||||
await cleanup();
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await cleanup();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export type { OrchestrationEvent, ScopeService, TerminalEvent, WsRpcClient };
|
||||
@@ -20,7 +20,8 @@
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
"test": "vitest run",
|
||||
"test:perf": "vitest run integration/perf"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { join } from "node:path";
|
||||
|
||||
import { seedPerfState } from "../integration/perf/seedPerfState.ts";
|
||||
import { getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__";
|
||||
const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__";
|
||||
const scenarioId = process.argv[2];
|
||||
|
||||
if (scenarioId !== "large_threads" && scenarioId !== "burst_base") {
|
||||
console.error(`Expected a perf seed scenario id, received '${scenarioId ?? "<missing>"}'.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const seeded = await seedPerfState(scenarioId);
|
||||
const scenario = getPerfSeedScenario(scenarioId);
|
||||
const scenarioProjectById = new Map(scenario.projects.map((project) => [project.id, project]));
|
||||
const scenarioThreadById = new Map(scenario.threads.map((thread) => [thread.id, thread]));
|
||||
const projectById = new Map(seeded.snapshot.projects.map((project) => [project.id, project]));
|
||||
const payload = JSON.stringify(
|
||||
{
|
||||
scenarioId: seeded.scenarioId,
|
||||
runParentDir: seeded.runParentDir,
|
||||
baseDir: seeded.baseDir,
|
||||
workspaceRoot: seeded.workspaceRoot,
|
||||
projectTitle: seeded.snapshot.projects[0]?.title ?? null,
|
||||
projectSummaries: seeded.snapshot.projects.map((project) => ({
|
||||
id: project.id,
|
||||
title: project.title,
|
||||
workspaceRoot:
|
||||
scenarioProjectById.get(project.id)?.workspaceDirectoryName !== undefined
|
||||
? join(seeded.baseDir, scenarioProjectById.get(project.id)?.workspaceDirectoryName ?? "")
|
||||
: project.workspaceRoot,
|
||||
threadCount: seeded.snapshot.threads.filter((thread) => thread.projectId === project.id)
|
||||
.length,
|
||||
})),
|
||||
threadSummaries: seeded.snapshot.threads.map((thread) => ({
|
||||
id: thread.id,
|
||||
projectId: thread.projectId,
|
||||
projectTitle: projectById.get(thread.projectId)?.title ?? null,
|
||||
title: thread.title,
|
||||
turnCount: scenarioThreadById.get(thread.id)?.turnCount ?? null,
|
||||
messageCount: thread.messages.length,
|
||||
activityCount: thread.activities.length,
|
||||
proposedPlanCount: thread.proposedPlans.length,
|
||||
checkpointCount: thread.checkpoints.length,
|
||||
})),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
process.stdout.write(`${PERF_SEED_JSON_START}\n${payload}\n${PERF_SEED_JSON_END}\n`);
|
||||
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
|
||||
if (input.fromTurnCount === input.toTurnCount) {
|
||||
@@ -149,7 +149,8 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
return turnDiff;
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
|
||||
input: OrchestrationGetFullThreadDiffInput,
|
||||
|
||||
@@ -86,139 +86,140 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
|
||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.captureCheckpoint";
|
||||
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
|
||||
"captureCheckpoint",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.captureCheckpoint";
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
||||
(tempDir) =>
|
||||
Effect.gen(function* () {
|
||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||
const commitEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
GIT_INDEX_FILE: tempIndexPath,
|
||||
GIT_AUTHOR_NAME: "T3 Code",
|
||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
yield* Effect.acquireUseRelease(
|
||||
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
|
||||
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
|
||||
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
|
||||
const commitEnv: NodeJS.ProcessEnv = {
|
||||
...process.env,
|
||||
GIT_INDEX_FILE: tempIndexPath,
|
||||
GIT_AUTHOR_NAME: "T3 Code",
|
||||
GIT_AUTHOR_EMAIL: "[email protected]",
|
||||
GIT_COMMITTER_NAME: "T3 Code",
|
||||
GIT_COMMITTER_EMAIL: "[email protected]",
|
||||
};
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["read-tree", "HEAD"],
|
||||
env: commitEnv,
|
||||
});
|
||||
}
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["read-tree", "HEAD"],
|
||||
env: commitEnv,
|
||||
});
|
||||
}
|
||||
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["add", "-A", "--", "."],
|
||||
env: commitEnv,
|
||||
});
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["add", "-A", "--", "."],
|
||||
env: commitEnv,
|
||||
});
|
||||
|
||||
const writeTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["write-tree"],
|
||||
env: commitEnv,
|
||||
});
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (treeOid.length === 0) {
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git write-tree",
|
||||
cwd: input.cwd,
|
||||
detail: "git write-tree returned an empty tree oid.",
|
||||
});
|
||||
}
|
||||
const writeTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["write-tree"],
|
||||
env: commitEnv,
|
||||
});
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (treeOid.length === 0) {
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git write-tree",
|
||||
cwd: input.cwd,
|
||||
detail: "git write-tree returned an empty tree oid.",
|
||||
});
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||
const commitTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["commit-tree", treeOid, "-m", message],
|
||||
env: commitEnv,
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (commitOid.length === 0) {
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git commit-tree",
|
||||
cwd: input.cwd,
|
||||
detail: "git commit-tree returned an empty commit oid.",
|
||||
});
|
||||
}
|
||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||
const commitTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["commit-tree", treeOid, "-m", message],
|
||||
env: commitEnv,
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (commitOid.length === 0) {
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git commit-tree",
|
||||
cwd: input.cwd,
|
||||
detail: "git commit-tree returned an empty commit oid.",
|
||||
});
|
||||
}
|
||||
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", input.checkpointRef, commitOid],
|
||||
});
|
||||
}),
|
||||
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
Effect.fail(
|
||||
new CheckpointInvariantError({
|
||||
operation: "CheckpointStore.captureCheckpoint",
|
||||
detail: "Failed to capture checkpoint.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", input.checkpointRef, commitOid],
|
||||
});
|
||||
}),
|
||||
(tempDir) => fs.remove(tempDir, { recursive: true }),
|
||||
).pipe(
|
||||
Effect.catchTags({
|
||||
PlatformError: (error) =>
|
||||
Effect.fail(
|
||||
new CheckpointInvariantError({
|
||||
operation: "CheckpointStore.captureCheckpoint",
|
||||
detail: "Failed to capture checkpoint.",
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
|
||||
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
|
||||
Effect.map((commit) => commit !== null),
|
||||
);
|
||||
|
||||
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.restoreCheckpoint";
|
||||
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
|
||||
"restoreCheckpoint",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.restoreCheckpoint";
|
||||
|
||||
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
||||
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
|
||||
|
||||
if (!commitOid && input.fallbackToHead === true) {
|
||||
commitOid = yield* resolveHeadCommit(input.cwd);
|
||||
}
|
||||
if (!commitOid && input.fallbackToHead === true) {
|
||||
commitOid = yield* resolveHeadCommit(input.cwd);
|
||||
}
|
||||
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
if (!commitOid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||
});
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["clean", "-fd", "--", "."],
|
||||
});
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["reset", "--quiet", "--", "."],
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||
});
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["clean", "-fd", "--", "."],
|
||||
});
|
||||
|
||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["reset", "--quiet", "--", "."],
|
||||
});
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointStore.diffCheckpoints";
|
||||
|
||||
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
|
||||
@@ -247,24 +248,26 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return result.stdout;
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const operation = "CheckpointStore.deleteCheckpointRefs";
|
||||
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
|
||||
"deleteCheckpointRefs",
|
||||
)(function* (input) {
|
||||
const operation = "CheckpointStore.deleteCheckpointRefs";
|
||||
|
||||
yield* Effect.forEach(
|
||||
input.checkpointRefs,
|
||||
(checkpointRef) =>
|
||||
git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", "-d", checkpointRef],
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
yield* Effect.forEach(
|
||||
input.checkpointRefs,
|
||||
(checkpointRef) =>
|
||||
git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", "-d", checkpointRef],
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
{ discard: true },
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
isGitRepository,
|
||||
|
||||
@@ -66,7 +66,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
* Spawn the Claude CLI with structured JSON output and return the parsed,
|
||||
* schema-validated result.
|
||||
*/
|
||||
const runClaudeJson = <S extends Schema.Top>({
|
||||
const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
@@ -82,131 +82,125 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ClaudeModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
||||
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
|
||||
getClaudeModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const settings = {
|
||||
...(typeof normalizedOptions?.thinking === "boolean"
|
||||
? { alwaysThinkingEnabled: normalizedOptions.thinking }
|
||||
: {}),
|
||||
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
|
||||
};
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
||||
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
|
||||
getClaudeModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const settings = {
|
||||
...(typeof normalizedOptions?.thinking === "boolean"
|
||||
? { alwaysThinkingEnabled: normalizedOptions.thinking }
|
||||
: {}),
|
||||
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
|
||||
};
|
||||
|
||||
const claudeSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.providers.claudeAgent,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
const claudeSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.providers.claudeAgent,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runClaudeCommand = Effect.gen(function* () {
|
||||
const command = ChildProcess.make(
|
||||
claudeSettings?.binaryPath || "claude",
|
||||
[
|
||||
"-p",
|
||||
"--output-format",
|
||||
"json",
|
||||
"--json-schema",
|
||||
jsonSchemaStr,
|
||||
"--model",
|
||||
resolveApiModelId(modelSelection),
|
||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
||||
"--dangerously-skip-permissions",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
|
||||
const command = ChildProcess.make(
|
||||
claudeSettings?.binaryPath || "claude",
|
||||
[
|
||||
"-p",
|
||||
"--output-format",
|
||||
"json",
|
||||
"--json-schema",
|
||||
jsonSchemaStr,
|
||||
"--model",
|
||||
resolveApiModelId(modelSelection),
|
||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
||||
"--dangerously-skip-permissions",
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
|
||||
normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
|
||||
),
|
||||
);
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError(
|
||||
"claude",
|
||||
operation,
|
||||
cause,
|
||||
"Failed to read Claude CLI exit code",
|
||||
),
|
||||
),
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Claude CLI command failed: ${detail}`
|
||||
: `Claude CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return stdout;
|
||||
});
|
||||
|
||||
const rawStdout = yield* runClaudeCommand().pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
|
||||
rawStdout,
|
||||
).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Claude CLI command failed: ${detail}`
|
||||
: `Claude CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
|
||||
return stdout;
|
||||
});
|
||||
|
||||
const rawStdout = yield* runClaudeCommand.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
|
||||
),
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
detail: "Claude CLI returned unexpected output format.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
),
|
||||
);
|
||||
|
||||
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
|
||||
rawStdout,
|
||||
).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude CLI returned unexpected output format.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Claude returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// TextGenerationShape methods
|
||||
|
||||
@@ -85,44 +85,43 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const materializeImageAttachments = (
|
||||
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
|
||||
_operation:
|
||||
| "generateCommitMessage"
|
||||
| "generatePrContent"
|
||||
| "generateBranchName"
|
||||
| "generateThreadTitle",
|
||||
attachments: BranchNameGenerationInput["attachments"],
|
||||
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
|
||||
Effect.gen(function* () {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return { imagePaths: [] };
|
||||
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
|
||||
if (!attachments || attachments.length === 0) {
|
||||
return { imagePaths: [] };
|
||||
}
|
||||
|
||||
const imagePaths: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const imagePaths: string[] = [];
|
||||
for (const attachment of attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const resolvedPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||
continue;
|
||||
}
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(resolvedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
continue;
|
||||
}
|
||||
imagePaths.push(resolvedPath);
|
||||
const resolvedPath = resolveAttachmentPath({
|
||||
attachmentsDir: serverConfig.attachmentsDir,
|
||||
attachment,
|
||||
});
|
||||
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
|
||||
continue;
|
||||
}
|
||||
return { imagePaths };
|
||||
});
|
||||
const fileInfo = yield* fileSystem
|
||||
.stat(resolvedPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
if (!fileInfo || fileInfo.type !== "File") {
|
||||
continue;
|
||||
}
|
||||
imagePaths.push(resolvedPath);
|
||||
}
|
||||
return { imagePaths };
|
||||
});
|
||||
|
||||
const runCodexJson = <S extends Schema.Top>({
|
||||
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
|
||||
operation,
|
||||
cwd,
|
||||
prompt,
|
||||
@@ -142,138 +141,137 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
imagePaths?: ReadonlyArray<string>;
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
modelSelection: CodexModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const codexSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.providers.codex,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
|
||||
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
|
||||
getCodexModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const outputPath = yield* writeTempFile(operation, "codex-output", "");
|
||||
|
||||
const codexSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.providers.codex,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
|
||||
getCodexModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const reasoningEffort =
|
||||
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
const command = ChildProcess.make(
|
||||
codexSettings?.binaryPath || "codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
modelSelection.model,
|
||||
"--config",
|
||||
`model_reasoning_effort="${reasoningEffort}"`,
|
||||
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const cleanup = Effect.all(
|
||||
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||
const reasoningEffort =
|
||||
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
|
||||
const command = ChildProcess.make(
|
||||
codexSettings?.binaryPath || "codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
modelSelection.model,
|
||||
"--config",
|
||||
`model_reasoning_effort="${reasoningEffort}"`,
|
||||
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
outputPath,
|
||||
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
|
||||
"-",
|
||||
],
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
},
|
||||
).pipe(Effect.asVoid);
|
||||
);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||
),
|
||||
onSome: () => Effect.void,
|
||||
const child = yield* commandSpawner
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
if (exitCode !== 0) {
|
||||
const stderrDetail = stderr.trim();
|
||||
const stdoutDetail = stdout.trim();
|
||||
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
|
||||
return yield* new TextGenerationError({
|
||||
operation,
|
||||
detail:
|
||||
detail.length > 0
|
||||
? `Codex CLI command failed: ${detail}`
|
||||
: `Codex CLI command failed with code ${exitCode}.`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const cleanup = Effect.all(
|
||||
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
yield* runCodexCommand().pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(CODEX_TIMEOUT_MS),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
|
||||
),
|
||||
onSome: () => Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Failed to read Codex output file.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return yield* fileSystem.readFileString(outputPath).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Failed to read Codex output file.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
|
||||
Effect.catchTag("SchemaError", (cause) =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation,
|
||||
detail: "Codex returned invalid structured output.",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
),
|
||||
);
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
|
||||
"CodexTextGeneration.generateCommitMessage",
|
||||
|
||||
@@ -31,6 +31,15 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const traeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "trae" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(traeLaunch, {
|
||||
command: "trae",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -89,6 +98,15 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const traeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(traeLineAndColumn, {
|
||||
command: "trae",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -256,6 +274,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
@@ -263,7 +282,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
+27
-28
@@ -220,38 +220,37 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
|
||||
});
|
||||
|
||||
export const launchDetached = Effect.fn("launchDetached")(function* (
|
||||
launch: EditorLaunch,
|
||||
): Effect.fn.Return<void, OpenError> {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
}
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const open = yield* Effect.tryPromise({
|
||||
|
||||
@@ -95,7 +95,9 @@ function createProviderServiceHarness(
|
||||
listSessions,
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
};
|
||||
|
||||
const emit = (event: LegacyProviderRuntimeEvent): void => {
|
||||
|
||||
@@ -499,21 +499,8 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
|
||||
event: Extract<
|
||||
OrchestrationEvent,
|
||||
{ type: "thread.turn-start-requested" | "thread.message-sent" }
|
||||
>,
|
||||
event: Extract<OrchestrationEvent, { type: "thread.turn-start-requested" }>,
|
||||
) {
|
||||
if (event.type === "thread.message-sent") {
|
||||
if (
|
||||
event.payload.role !== "user" ||
|
||||
event.payload.streaming ||
|
||||
event.payload.turnId !== null
|
||||
) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const threadId = event.payload.threadId;
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
@@ -686,7 +673,7 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {
|
||||
if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
|
||||
if (event.type === "thread.turn-start-requested") {
|
||||
yield* ensurePreTurnBaselineFromDomainTurnStart(event);
|
||||
return;
|
||||
}
|
||||
@@ -772,7 +759,6 @@ const make = Effect.gen(function* () {
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (
|
||||
event.type !== "thread.turn-start-requested" &&
|
||||
event.type !== "thread.message-sent" &&
|
||||
event.type !== "thread.checkpoint-revert-requested" &&
|
||||
event.type !== "thread.turn-diff-completed"
|
||||
) {
|
||||
|
||||
@@ -623,31 +623,46 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
switch (event.type) {
|
||||
case "thread.message-sent": {
|
||||
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const existingMessage = existingRows.find(
|
||||
(row) => row.messageId === event.payload.messageId,
|
||||
);
|
||||
const nextText =
|
||||
existingMessage && event.payload.streaming
|
||||
? `${existingMessage.text}${event.payload.text}`
|
||||
: existingMessage && event.payload.text.length === 0
|
||||
? existingMessage.text
|
||||
: event.payload.text;
|
||||
const nextAttachments =
|
||||
event.payload.attachments !== undefined
|
||||
? yield* materializeAttachmentsForProjection({
|
||||
attachments: event.payload.attachments,
|
||||
})
|
||||
: existingMessage?.attachments;
|
||||
: undefined;
|
||||
if (event.payload.streaming) {
|
||||
yield* projectionThreadMessageRepository.appendTextDelta({
|
||||
messageId: event.payload.messageId,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
role: event.payload.role,
|
||||
delta: event.payload.text,
|
||||
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
|
||||
isStreaming: true,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const existingMessage = yield* projectionThreadMessageRepository
|
||||
.getByMessageId({
|
||||
messageId: event.payload.messageId,
|
||||
})
|
||||
.pipe(Effect.map(Option.getOrUndefined));
|
||||
const nextText =
|
||||
existingMessage !== undefined && event.payload.text.length === 0
|
||||
? existingMessage.text
|
||||
: event.payload.text;
|
||||
const persistedAttachments = nextAttachments ?? existingMessage?.attachments;
|
||||
yield* projectionThreadMessageRepository.upsert({
|
||||
messageId: event.payload.messageId,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.turnId,
|
||||
role: event.payload.role,
|
||||
text: nextText,
|
||||
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
|
||||
...(persistedAttachments !== undefined
|
||||
? { attachments: [...persistedAttachments] }
|
||||
: {}),
|
||||
isStreaming: event.payload.streaming,
|
||||
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
|
||||
@@ -207,7 +207,9 @@ describe("ProviderCommandReactor", () => {
|
||||
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
|
||||
}),
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
};
|
||||
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
|
||||
@@ -724,39 +724,40 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const processDomainEvent = (event: ProviderIntentEvent) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.runtime-mode-set": {
|
||||
const thread = yield* resolveThread(event.payload.threadId);
|
||||
if (!thread?.session || thread.session.status === "stopped") {
|
||||
return;
|
||||
}
|
||||
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(
|
||||
event.payload.threadId,
|
||||
event.occurredAt,
|
||||
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
|
||||
);
|
||||
const processDomainEvent = Effect.fn("processDomainEvent")(function* (
|
||||
event: ProviderIntentEvent,
|
||||
) {
|
||||
switch (event.type) {
|
||||
case "thread.runtime-mode-set": {
|
||||
const thread = yield* resolveThread(event.payload.threadId);
|
||||
if (!thread?.session || thread.session.status === "stopped") {
|
||||
return;
|
||||
}
|
||||
case "thread.turn-start-requested":
|
||||
yield* processTurnStartRequested(event);
|
||||
return;
|
||||
case "thread.turn-interrupt-requested":
|
||||
yield* processTurnInterruptRequested(event);
|
||||
return;
|
||||
case "thread.approval-response-requested":
|
||||
yield* processApprovalResponseRequested(event);
|
||||
return;
|
||||
case "thread.user-input-response-requested":
|
||||
yield* processUserInputResponseRequested(event);
|
||||
return;
|
||||
case "thread.session-stop-requested":
|
||||
yield* processSessionStopRequested(event);
|
||||
return;
|
||||
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(
|
||||
event.payload.threadId,
|
||||
event.occurredAt,
|
||||
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
|
||||
);
|
||||
return;
|
||||
}
|
||||
});
|
||||
case "thread.turn-start-requested":
|
||||
yield* processTurnStartRequested(event);
|
||||
return;
|
||||
case "thread.turn-interrupt-requested":
|
||||
yield* processTurnInterruptRequested(event);
|
||||
return;
|
||||
case "thread.approval-response-requested":
|
||||
yield* processApprovalResponseRequested(event);
|
||||
return;
|
||||
case "thread.user-input-response-requested":
|
||||
yield* processUserInputResponseRequested(event);
|
||||
return;
|
||||
case "thread.session-stop-requested":
|
||||
yield* processSessionStopRequested(event);
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const processDomainEventSafely = (event: ProviderIntentEvent) =>
|
||||
processDomainEvent(event).pipe(
|
||||
|
||||
@@ -97,7 +97,9 @@ function createProviderServiceHarness() {
|
||||
listSessions: () => Effect.succeed([...runtimeSessions]),
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
};
|
||||
|
||||
const setSession = (session: ProviderSession): void => {
|
||||
|
||||
@@ -11,7 +11,9 @@ const makeRuntimeReceiptBus = Effect.gen(function* () {
|
||||
|
||||
return {
|
||||
publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid),
|
||||
stream: Stream.fromPubSub(pubSub),
|
||||
get stream() {
|
||||
return Stream.fromPubSub(pubSub);
|
||||
},
|
||||
} satisfies RuntimeReceiptBusShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { Effect, Stream } from "effect";
|
||||
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
import { makePerfProviderAdapter } from "./PerfProviderAdapter.ts";
|
||||
|
||||
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
const STREAM_SAMPLE_EVENT_COUNT = 96;
|
||||
|
||||
describe("PerfProviderAdapter", () => {
|
||||
const previousScenarioEnv = process.env[PERF_SCENARIO_ENV];
|
||||
|
||||
afterEach(() => {
|
||||
if (previousScenarioEnv === undefined) {
|
||||
delete process.env[PERF_SCENARIO_ENV];
|
||||
return;
|
||||
}
|
||||
process.env[PERF_SCENARIO_ENV] = previousScenarioEnv;
|
||||
});
|
||||
|
||||
it("emits canonical runtime events for the dense assistant stream scenario", async () => {
|
||||
process.env[PERF_SCENARIO_ENV] = "dense_assistant_stream";
|
||||
const adapter = await Effect.runPromise(makePerfProviderAdapter);
|
||||
const threadId = PERF_CATALOG_IDS.burstBase.burstThreadId;
|
||||
|
||||
await Effect.runPromise(
|
||||
adapter.startSession({
|
||||
threadId,
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEventsPromise = Effect.runPromise(
|
||||
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "exercise the dense perf scenario",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEvents = Array.from(await firstEventsPromise);
|
||||
expect(firstEvents.filter((event) => event.type === "turn.started")).toHaveLength(3);
|
||||
expect(new Set(firstEvents.slice(0, 18).map((event) => String(event.threadId)))).toEqual(
|
||||
new Set([
|
||||
String(threadId),
|
||||
String(PERF_CATALOG_IDS.burstBase.navigationThreadId),
|
||||
String(PERF_CATALOG_IDS.burstBase.fillerThreadId),
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
firstEvents.some(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
|
||||
event.type === "content.delta" &&
|
||||
event.payload.delta.includes("Navigation lane"),
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
firstEvents.some(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message",
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
firstEvents.some(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.fillerThreadId &&
|
||||
event.type === "item.updated" &&
|
||||
event.payload.itemType === "command_execution",
|
||||
),
|
||||
).toBe(true);
|
||||
|
||||
const firstBurstFollowupCompletionIndex = firstEvents.findIndex(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message" &&
|
||||
String(event.itemId ?? "").includes("followup"),
|
||||
);
|
||||
const burstWorklogIdsBeforeFollowup = new Set(
|
||||
firstEvents
|
||||
.slice(0, firstBurstFollowupCompletionIndex)
|
||||
.filter(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.started" &&
|
||||
event.payload.itemType === "command_execution",
|
||||
)
|
||||
.map((event) => String(event.itemId)),
|
||||
);
|
||||
const burstAssistantMessageLengths = firstEvents
|
||||
.flatMap((event) => {
|
||||
if (
|
||||
event.threadId !== threadId ||
|
||||
event.type !== "item.completed" ||
|
||||
event.payload.itemType !== "assistant_message" ||
|
||||
event.payload.detail === undefined
|
||||
) {
|
||||
return [];
|
||||
}
|
||||
return [event.payload.detail.length];
|
||||
})
|
||||
.slice(0, 4);
|
||||
|
||||
expect(firstBurstFollowupCompletionIndex).toBeGreaterThan(0);
|
||||
expect(burstWorklogIdsBeforeFollowup.size).toBeGreaterThanOrEqual(3);
|
||||
expect(new Set(burstAssistantMessageLengths).size).toBeGreaterThan(1);
|
||||
});
|
||||
|
||||
it("assigns fresh runtime ids when the same burst thread is sent twice", async () => {
|
||||
process.env[PERF_SCENARIO_ENV] = "dense_assistant_stream";
|
||||
const adapter = await Effect.runPromise(makePerfProviderAdapter);
|
||||
const threadId = PERF_CATALOG_IDS.burstBase.burstThreadId;
|
||||
|
||||
await Effect.runPromise(
|
||||
adapter.startSession({
|
||||
threadId,
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEventsPromise = Effect.runPromise(
|
||||
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "first dense perf pass",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const firstEvents = Array.from(await firstEventsPromise);
|
||||
|
||||
const secondEventsPromise = Effect.runPromise(
|
||||
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
adapter.sendTurn({
|
||||
threadId,
|
||||
input: "second dense perf pass",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
const secondEvents = Array.from(await secondEventsPromise);
|
||||
|
||||
const firstNavigationTurnStarted = firstEvents.find(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
|
||||
event.type === "turn.started",
|
||||
);
|
||||
const secondNavigationTurnStarted = secondEvents.find(
|
||||
(event) =>
|
||||
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
|
||||
event.type === "turn.started",
|
||||
);
|
||||
const firstBurstAssistantCompletion = firstEvents.find(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message",
|
||||
);
|
||||
const secondBurstAssistantCompletion = secondEvents.find(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
event.type === "item.completed" &&
|
||||
event.payload.itemType === "assistant_message",
|
||||
);
|
||||
const secondRunNamespaceSuffix = `--perf-run-${String(threadId)}-0002`;
|
||||
|
||||
expect(firstNavigationTurnStarted?.turnId).toBe(PERF_CATALOG_IDS.provider.navigationLiveTurnId);
|
||||
expect(firstBurstAssistantCompletion?.itemId).toBeDefined();
|
||||
expect(secondNavigationTurnStarted?.turnId).toBeDefined();
|
||||
expect(secondBurstAssistantCompletion?.itemId).toBeDefined();
|
||||
expect(secondNavigationTurnStarted?.turnId).not.toBe(firstNavigationTurnStarted?.turnId);
|
||||
expect(secondBurstAssistantCompletion?.itemId).not.toBe(firstBurstAssistantCompletion?.itemId);
|
||||
expect(String(secondNavigationTurnStarted?.turnId)).toContain(secondRunNamespaceSuffix);
|
||||
expect(String(secondBurstAssistantCompletion?.itemId)).toContain(secondRunNamespaceSuffix);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,456 @@
|
||||
import {
|
||||
EventId,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
RuntimeSessionId,
|
||||
TurnId,
|
||||
type ApprovalRequestId,
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderRuntimeEvent,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
type ProviderUserInputAnswers,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
import {
|
||||
getPerfProviderScenario,
|
||||
type PerfProviderScenario,
|
||||
type TimedFixtureProviderRuntimeEvent,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import {
|
||||
ProviderAdapterSessionNotFoundError,
|
||||
ProviderAdapterValidationError,
|
||||
type ProviderAdapterError,
|
||||
} from "../provider/Errors.ts";
|
||||
import type {
|
||||
ProviderAdapterShape,
|
||||
ProviderThreadSnapshot,
|
||||
ProviderThreadTurnSnapshot,
|
||||
} from "../provider/Services/ProviderAdapter.ts";
|
||||
import { getPerfProviderScenarioId } from "./config.ts";
|
||||
|
||||
interface PerfSessionState {
|
||||
session: ProviderSession;
|
||||
snapshot: ProviderThreadSnapshot;
|
||||
turnCount: number;
|
||||
pendingTimers: Set<ReturnType<typeof setTimeout>>;
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function sessionNotFound(threadId: ThreadId): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider: "codex",
|
||||
threadId: String(threadId),
|
||||
});
|
||||
}
|
||||
|
||||
function resolvePerfScenario(inputText: string | undefined): PerfProviderScenario {
|
||||
const scenarioId = getPerfProviderScenarioId();
|
||||
if (scenarioId) {
|
||||
return getPerfProviderScenario(scenarioId);
|
||||
}
|
||||
|
||||
const trimmedInput = inputText?.trim() || "perf request";
|
||||
return {
|
||||
id: "dense_assistant_stream",
|
||||
provider: "codex",
|
||||
sentinelText: `PERF_STREAM_SENTINEL:fallback:${trimmedInput}`,
|
||||
totalDurationMs: 48,
|
||||
events: [
|
||||
{
|
||||
delayMs: 0,
|
||||
type: "turn.started",
|
||||
payload: {
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
},
|
||||
{
|
||||
delayMs: 16,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: `Perf fallback response for: ${trimmedInput}. `,
|
||||
},
|
||||
},
|
||||
{
|
||||
delayMs: 32,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: `PERF_STREAM_SENTINEL:fallback:${trimmedInput}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
delayMs: 48,
|
||||
type: "turn.completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function toIdleSession(session: ProviderSession, updatedAt: string): ProviderSession {
|
||||
const { activeTurnId: _activeTurnId, ...rest } = session;
|
||||
return {
|
||||
...rest,
|
||||
status: "ready",
|
||||
updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
function namespacePerfFixtureId(
|
||||
baseId: string,
|
||||
sourceThreadId: ThreadId,
|
||||
runIndex: number,
|
||||
): string {
|
||||
return `${baseId}--perf-run-${String(sourceThreadId)}-${runIndex.toString().padStart(4, "0")}`;
|
||||
}
|
||||
|
||||
function buildRuntimeEvent(input: {
|
||||
readonly template: TimedFixtureProviderRuntimeEvent;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId;
|
||||
readonly startedAtMs: number;
|
||||
readonly index: number;
|
||||
readonly runIndex: number;
|
||||
}): ProviderRuntimeEvent {
|
||||
const eventThreadId = input.template.threadId ?? input.threadId;
|
||||
const eventTurnId =
|
||||
input.template.turnId === undefined
|
||||
? input.turnId
|
||||
: input.runIndex === 1
|
||||
? input.template.turnId
|
||||
: TurnId.makeUnsafe(
|
||||
namespacePerfFixtureId(String(input.template.turnId), input.threadId, input.runIndex),
|
||||
);
|
||||
const createdAt = new Date(input.startedAtMs + (input.template.delayMs ?? 0)).toISOString();
|
||||
return {
|
||||
type: input.template.type,
|
||||
eventId: EventId.makeUnsafe(
|
||||
`perf-runtime:${String(eventThreadId)}:${String(eventTurnId)}:${input.index.toString().padStart(4, "0")}`,
|
||||
),
|
||||
provider: "codex",
|
||||
threadId: eventThreadId,
|
||||
turnId: eventTurnId,
|
||||
createdAt,
|
||||
...(input.template.itemId
|
||||
? {
|
||||
itemId: RuntimeItemId.makeUnsafe(
|
||||
input.runIndex === 1
|
||||
? input.template.itemId
|
||||
: namespacePerfFixtureId(input.template.itemId, input.threadId, input.runIndex),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(input.template.requestId
|
||||
? {
|
||||
requestId: RuntimeRequestId.makeUnsafe(
|
||||
input.runIndex === 1
|
||||
? input.template.requestId
|
||||
: namespacePerfFixtureId(input.template.requestId, input.threadId, input.runIndex),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
payload: input.template.payload,
|
||||
} as ProviderRuntimeEvent;
|
||||
}
|
||||
|
||||
export const makePerfProviderAdapter = Effect.gen(function* () {
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const sessions = new Map<ThreadId, PerfSessionState>();
|
||||
|
||||
const clearPendingTimers = (threadId: ThreadId) =>
|
||||
Effect.sync(() => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
for (const timer of state.pendingTimers) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
state.pendingTimers.clear();
|
||||
});
|
||||
|
||||
const scheduleRuntimeEvent = (input: {
|
||||
readonly state: PerfSessionState;
|
||||
readonly event: ProviderRuntimeEvent;
|
||||
readonly delayMs: number;
|
||||
readonly onAfterEmit?: () => void;
|
||||
}) =>
|
||||
Effect.sync(() => {
|
||||
const timer = setTimeout(() => {
|
||||
input.state.pendingTimers.delete(timer);
|
||||
Effect.runFork(
|
||||
Queue.offer(runtimeEvents, input.event).pipe(
|
||||
Effect.tap(() => Effect.sync(() => input.onAfterEmit?.())),
|
||||
Effect.asVoid,
|
||||
),
|
||||
);
|
||||
}, input.delayMs);
|
||||
input.state.pendingTimers.add(timer);
|
||||
});
|
||||
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (
|
||||
input: ProviderSessionStartInput,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== "codex") {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: "codex",
|
||||
operation: "startSession",
|
||||
issue: `Perf provider only supports codex sessions, received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
const createdAt = nowIso();
|
||||
const session: ProviderSession = {
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId: input.threadId,
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(input.modelSelection?.model ? { model: input.modelSelection.model } : {}),
|
||||
resumeCursor:
|
||||
input.resumeCursor ??
|
||||
RuntimeSessionId.makeUnsafe(`perf-resume:${String(input.threadId)}:${Date.now()}`),
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
};
|
||||
|
||||
sessions.set(input.threadId, {
|
||||
session,
|
||||
snapshot: {
|
||||
threadId: input.threadId,
|
||||
turns: [],
|
||||
},
|
||||
turnCount: 0,
|
||||
pendingTimers: new Set(),
|
||||
});
|
||||
|
||||
return session;
|
||||
});
|
||||
|
||||
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (
|
||||
input: ProviderSendTurnInput,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(input.threadId);
|
||||
if (!state) {
|
||||
return yield* Effect.fail(sessionNotFound(input.threadId));
|
||||
}
|
||||
|
||||
yield* clearPendingTimers(input.threadId);
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnId = TurnId.makeUnsafe(
|
||||
`perf-turn:${String(input.threadId)}:${state.turnCount.toString().padStart(4, "0")}`,
|
||||
);
|
||||
const scenario = resolvePerfScenario(input.input);
|
||||
const startedAtMs = Date.now();
|
||||
const sentAt = new Date(startedAtMs).toISOString();
|
||||
|
||||
state.session = {
|
||||
...state.session,
|
||||
status: "running",
|
||||
activeTurnId: turnId,
|
||||
updatedAt: sentAt,
|
||||
};
|
||||
|
||||
const userTurnItem = {
|
||||
type: "userMessage",
|
||||
content: [{ type: "text", text: input.input ?? "" }],
|
||||
} as const;
|
||||
const nextTurn: ProviderThreadTurnSnapshot = {
|
||||
id: turnId,
|
||||
items: [userTurnItem],
|
||||
};
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: [...state.snapshot.turns, nextTurn],
|
||||
};
|
||||
|
||||
let assistantText = "";
|
||||
const updateAssistantSnapshot = (completedAt: string) => {
|
||||
state.session = toIdleSession(state.session, completedAt);
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: state.snapshot.turns.map((turn) =>
|
||||
turn.id === turnId
|
||||
? {
|
||||
...turn,
|
||||
items:
|
||||
assistantText.length > 0
|
||||
? [...turn.items, { type: "agentMessage", text: assistantText }]
|
||||
: turn.items,
|
||||
}
|
||||
: turn,
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
yield* Effect.forEach(
|
||||
scenario.events,
|
||||
(template, index) => {
|
||||
const event = buildRuntimeEvent({
|
||||
template,
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
startedAtMs,
|
||||
index,
|
||||
runIndex: state.turnCount,
|
||||
});
|
||||
const delayMs = template.delayMs ?? 0;
|
||||
return scheduleRuntimeEvent({
|
||||
state,
|
||||
event,
|
||||
delayMs,
|
||||
onAfterEmit: () => {
|
||||
if (
|
||||
event.threadId === input.threadId &&
|
||||
event.type === "content.delta" &&
|
||||
event.payload.streamKind === "assistant_text"
|
||||
) {
|
||||
assistantText += event.payload.delta;
|
||||
}
|
||||
if (event.threadId === input.threadId && event.type === "turn.completed") {
|
||||
updateAssistantSnapshot(event.createdAt);
|
||||
}
|
||||
},
|
||||
});
|
||||
},
|
||||
{ concurrency: 1 },
|
||||
);
|
||||
|
||||
return {
|
||||
threadId: input.threadId,
|
||||
turnId,
|
||||
} satisfies ProviderTurnStartResult;
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
|
||||
threadId,
|
||||
turnId,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return yield* Effect.fail(sessionNotFound(threadId));
|
||||
}
|
||||
yield* clearPendingTimers(threadId);
|
||||
const interruptedTurnId = turnId ?? state.session.activeTurnId;
|
||||
state.session = toIdleSession(state.session, nowIso());
|
||||
if (interruptedTurnId) {
|
||||
yield* Queue.offer(runtimeEvents, {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(
|
||||
`perf-runtime:${String(threadId)}:${String(interruptedTurnId)}:interrupted`,
|
||||
),
|
||||
provider: "codex",
|
||||
threadId,
|
||||
turnId: interruptedTurnId,
|
||||
createdAt: nowIso(),
|
||||
payload: {
|
||||
state: "interrupted",
|
||||
},
|
||||
} satisfies ProviderRuntimeEvent);
|
||||
}
|
||||
});
|
||||
|
||||
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
|
||||
threadId,
|
||||
_requestId: ApprovalRequestId,
|
||||
_decision: ProviderApprovalDecision,
|
||||
) => (sessions.has(threadId) ? Effect.void : Effect.fail(sessionNotFound(threadId)));
|
||||
|
||||
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
|
||||
threadId,
|
||||
_requestId,
|
||||
_answers: ProviderUserInputAnswers,
|
||||
) => (sessions.has(threadId) ? Effect.void : Effect.fail(sessionNotFound(threadId)));
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
|
||||
Effect.gen(function* () {
|
||||
if (!sessions.has(threadId)) {
|
||||
return yield* Effect.fail(sessionNotFound(threadId));
|
||||
}
|
||||
yield* clearPendingTimers(threadId);
|
||||
sessions.delete(threadId);
|
||||
});
|
||||
|
||||
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
|
||||
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
|
||||
Effect.succeed(sessions.has(threadId));
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) =>
|
||||
sessions.has(threadId)
|
||||
? Effect.succeed(sessions.get(threadId)!.snapshot)
|
||||
: Effect.fail(sessionNotFound(threadId));
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
threadId,
|
||||
numTurns,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return yield* Effect.fail(sessionNotFound(threadId));
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: "codex",
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer between 0 and the current turn count.",
|
||||
});
|
||||
}
|
||||
state.snapshot = {
|
||||
threadId: state.snapshot.threadId,
|
||||
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
|
||||
};
|
||||
state.turnCount = state.snapshot.turns.length;
|
||||
return state.snapshot;
|
||||
});
|
||||
|
||||
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.forEach(
|
||||
Array.from(sessions.keys()),
|
||||
(threadId) => clearPendingTimers(threadId),
|
||||
{
|
||||
concurrency: "unbounded",
|
||||
},
|
||||
);
|
||||
sessions.clear();
|
||||
});
|
||||
|
||||
return {
|
||||
provider: "codex",
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEvents);
|
||||
},
|
||||
} satisfies ProviderAdapterShape<ProviderAdapterError>;
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import { ProviderSessionRuntimeRepositoryLive } from "../persistence/Layers/ProviderSessionRuntime.ts";
|
||||
import { ProviderUnsupportedError } from "../provider/Errors.ts";
|
||||
import { makeProviderServiceLive } from "../provider/Layers/ProviderService.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ProviderAdapterRegistry } from "../provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { makePerfProviderAdapter } from "./PerfProviderAdapter.ts";
|
||||
|
||||
export const PerfProviderLayerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const adapter = yield* makePerfProviderAdapter;
|
||||
const adapterRegistryLayer = Layer.succeed(ProviderAdapterRegistry, {
|
||||
getByProvider: (provider) =>
|
||||
provider === adapter.provider
|
||||
? Effect.succeed(adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed([adapter.provider]),
|
||||
} as typeof ProviderAdapterRegistry.Service);
|
||||
|
||||
return makeProviderServiceLive().pipe(
|
||||
Layer.provide(adapterRegistryLayer),
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,160 @@
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ServerProvider,
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect";
|
||||
|
||||
import { getClaudeModelCapabilities } from "../provider/Layers/ClaudeProvider.ts";
|
||||
import { getCodexModelCapabilities } from "../provider/Layers/CodexProvider.ts";
|
||||
import { ServerSettingsService } from "../serverSettings.ts";
|
||||
import {
|
||||
ProviderRegistry,
|
||||
type ProviderRegistryShape,
|
||||
} from "../provider/Services/ProviderRegistry.ts";
|
||||
|
||||
const makeProviderModel = (input: {
|
||||
readonly slug: string;
|
||||
readonly name: string;
|
||||
readonly capabilities: ServerProviderModel["capabilities"];
|
||||
}): ServerProviderModel => ({
|
||||
slug: input.slug,
|
||||
name: input.name,
|
||||
isCustom: false,
|
||||
capabilities: input.capabilities,
|
||||
});
|
||||
|
||||
const CODEX_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
makeProviderModel({
|
||||
slug: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
name: "GPT-5.4",
|
||||
capabilities: getCodexModelCapabilities(DEFAULT_MODEL_BY_PROVIDER.codex),
|
||||
}),
|
||||
];
|
||||
|
||||
const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
makeProviderModel({
|
||||
slug: DEFAULT_MODEL_BY_PROVIDER.claudeAgent,
|
||||
name: "Claude Sonnet 4.6",
|
||||
capabilities: getClaudeModelCapabilities(DEFAULT_MODEL_BY_PROVIDER.claudeAgent),
|
||||
}),
|
||||
];
|
||||
|
||||
const makeProviderSnapshot = (input: {
|
||||
readonly provider: ServerProvider["provider"];
|
||||
readonly enabled: boolean;
|
||||
readonly checkedAt: string;
|
||||
}): ServerProvider => {
|
||||
if (input.provider === "codex") {
|
||||
return {
|
||||
provider: "codex",
|
||||
enabled: input.enabled,
|
||||
installed: true,
|
||||
version: "perf-fixture",
|
||||
status: input.enabled ? "ready" : "disabled",
|
||||
auth: input.enabled
|
||||
? {
|
||||
status: "authenticated",
|
||||
type: "perf",
|
||||
label: "Local perf harness",
|
||||
}
|
||||
: {
|
||||
status: "unknown",
|
||||
},
|
||||
checkedAt: input.checkedAt,
|
||||
message: input.enabled ? "Perf fixture provider active." : "Disabled in T3 Code settings.",
|
||||
models: CODEX_MODELS,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
provider: "claudeAgent",
|
||||
enabled: input.enabled,
|
||||
installed: false,
|
||||
version: null,
|
||||
status: input.enabled ? "warning" : "disabled",
|
||||
auth: {
|
||||
status: "unknown",
|
||||
},
|
||||
checkedAt: input.checkedAt,
|
||||
message: input.enabled
|
||||
? "Perf harness only stubs Codex runtime sessions."
|
||||
: "Disabled in T3 Code settings.",
|
||||
models: CLAUDE_MODELS,
|
||||
};
|
||||
};
|
||||
|
||||
const loadPerfProviderSnapshots = Effect.fn("loadPerfProviderSnapshots")(function* (input: {
|
||||
readonly serverSettings: ServerSettingsService["Service"];
|
||||
}) {
|
||||
const settings = yield* input.serverSettings.getSettings;
|
||||
const checkedAt = new Date().toISOString();
|
||||
return [
|
||||
makeProviderSnapshot({
|
||||
provider: "codex",
|
||||
enabled: settings.providers.codex.enabled,
|
||||
checkedAt,
|
||||
}),
|
||||
makeProviderSnapshot({
|
||||
provider: "claudeAgent",
|
||||
enabled: settings.providers.claudeAgent.enabled,
|
||||
checkedAt,
|
||||
}),
|
||||
] as const;
|
||||
});
|
||||
|
||||
const loadPerfProviderSnapshotsSafely = (
|
||||
serverSettings: ServerSettingsService["Service"],
|
||||
fallback: ReadonlyArray<ServerProvider>,
|
||||
) =>
|
||||
loadPerfProviderSnapshots({ serverSettings }).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => fallback),
|
||||
);
|
||||
|
||||
export const PerfProviderRegistryLive = Layer.effect(
|
||||
ProviderRegistry,
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
|
||||
yield* loadPerfProviderSnapshotsSafely(serverSettings, [
|
||||
makeProviderSnapshot({
|
||||
provider: "codex",
|
||||
enabled: true,
|
||||
checkedAt: new Date().toISOString(),
|
||||
}),
|
||||
makeProviderSnapshot({
|
||||
provider: "claudeAgent",
|
||||
enabled: false,
|
||||
checkedAt: new Date().toISOString(),
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
const refreshProviders = Effect.fn("refreshPerfProviders")(function* () {
|
||||
const previous = yield* Ref.get(providersRef);
|
||||
const next = yield* loadPerfProviderSnapshotsSafely(serverSettings, previous);
|
||||
yield* Ref.set(providersRef, next);
|
||||
if (!Equal.equals(previous, next)) {
|
||||
yield* PubSub.publish(changesPubSub, next);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(serverSettings.streamChanges, () => refreshProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
return {
|
||||
getProviders: Ref.get(providersRef),
|
||||
refresh: (_provider) => refreshProviders(),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
} satisfies ProviderRegistryShape;
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { PerfProviderScenarioId } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
export const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
|
||||
export const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
export const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
|
||||
export const PERF_HEADFUL_ENV = "T3CODE_PERF_HEADFUL";
|
||||
|
||||
export function isPerfProviderEnabled(): boolean {
|
||||
return process.env[PERF_PROVIDER_ENV] === "1";
|
||||
}
|
||||
|
||||
export function getPerfProviderScenarioId(): PerfProviderScenarioId | null {
|
||||
const rawScenarioId = process.env[PERF_SCENARIO_ENV]?.trim();
|
||||
if (rawScenarioId === "dense_assistant_stream" || rawScenarioId === "parallel_assistant_stream") {
|
||||
return rawScenarioId;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { MessageId, ThreadId } from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { Effect, Layer, Option } from "effect";
|
||||
|
||||
import { ProjectionThreadMessageRepository } from "../Services/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadMessageRepositoryLive } from "./ProjectionThreadMessages.ts";
|
||||
@@ -103,4 +103,84 @@ layer("ProjectionThreadMessageRepository", (it) => {
|
||||
assert.deepEqual(rows[0]?.attachments, []);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("looks up a projected message by id", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
const threadId = ThreadId.makeUnsafe("thread-get-by-message-id");
|
||||
const messageId = MessageId.makeUnsafe("message-get-by-message-id");
|
||||
const createdAt = "2026-02-28T19:20:00.000Z";
|
||||
const updatedAt = "2026-02-28T19:20:01.000Z";
|
||||
|
||||
yield* repository.upsert({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "assistant",
|
||||
text: "lookup me",
|
||||
isStreaming: false,
|
||||
createdAt,
|
||||
updatedAt,
|
||||
});
|
||||
|
||||
const maybeRow = yield* repository.getByMessageId({ messageId });
|
||||
assert.isTrue(Option.isSome(maybeRow));
|
||||
const row = Option.getOrThrow(maybeRow);
|
||||
assert.equal(row.messageId, messageId);
|
||||
assert.equal(row.threadId, threadId);
|
||||
assert.equal(row.text, "lookup me");
|
||||
assert.equal(row.createdAt, createdAt);
|
||||
assert.equal(row.updatedAt, updatedAt);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("appends streaming deltas without losing createdAt or attachments", () =>
|
||||
Effect.gen(function* () {
|
||||
const repository = yield* ProjectionThreadMessageRepository;
|
||||
const threadId = ThreadId.makeUnsafe("thread-append-delta");
|
||||
const messageId = MessageId.makeUnsafe("message-append-delta");
|
||||
const createdAt = "2026-02-28T19:30:00.000Z";
|
||||
const persistedAttachments = [
|
||||
{
|
||||
type: "image" as const,
|
||||
id: "thread-append-delta-att-1",
|
||||
name: "example.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
];
|
||||
|
||||
yield* repository.appendTextDelta({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "assistant",
|
||||
delta: "Hello",
|
||||
attachments: persistedAttachments,
|
||||
isStreaming: true,
|
||||
createdAt,
|
||||
updatedAt: "2026-02-28T19:30:01.000Z",
|
||||
});
|
||||
|
||||
yield* repository.appendTextDelta({
|
||||
messageId,
|
||||
threadId,
|
||||
turnId: null,
|
||||
role: "assistant",
|
||||
delta: " world",
|
||||
isStreaming: true,
|
||||
createdAt: "2026-02-28T19:30:05.000Z",
|
||||
updatedAt: "2026-02-28T19:30:06.000Z",
|
||||
});
|
||||
|
||||
const maybeRow = yield* repository.getByMessageId({ messageId });
|
||||
assert.isTrue(Option.isSome(maybeRow));
|
||||
const row = Option.getOrThrow(maybeRow);
|
||||
assert.equal(row.text, "Hello world");
|
||||
assert.equal(row.createdAt, createdAt);
|
||||
assert.equal(row.updatedAt, "2026-02-28T19:30:06.000Z");
|
||||
assert.deepEqual(row.attachments, persistedAttachments);
|
||||
assert.isTrue(row.isStreaming);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,10 +1,12 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import { Effect, Layer, Option, Schema, Struct } from "effect";
|
||||
import { ChatAttachment } from "@t3tools/contracts";
|
||||
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
AppendProjectionThreadMessageDeltaInput,
|
||||
GetProjectionThreadMessageInput,
|
||||
ProjectionThreadMessageRepository,
|
||||
type ProjectionThreadMessageRepositoryShape,
|
||||
DeleteProjectionThreadMessagesInput,
|
||||
@@ -18,6 +20,19 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||
}),
|
||||
);
|
||||
type ProjectionThreadMessageDbRow = typeof ProjectionThreadMessageDbRowSchema.Type;
|
||||
|
||||
const toProjectionThreadMessage = (row: ProjectionThreadMessageDbRow) => ({
|
||||
messageId: row.messageId,
|
||||
threadId: row.threadId,
|
||||
turnId: row.turnId,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
isStreaming: row.isStreaming === 1,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
...(row.attachments !== null ? { attachments: row.attachments } : {}),
|
||||
});
|
||||
|
||||
const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
@@ -95,6 +110,70 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getProjectionThreadMessageRow = SqlSchema.findOneOption({
|
||||
Request: GetProjectionThreadMessageInput,
|
||||
Result: ProjectionThreadMessageDbRowSchema,
|
||||
execute: ({ messageId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
message_id AS "messageId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
role,
|
||||
text,
|
||||
attachments_json AS "attachments",
|
||||
is_streaming AS "isStreaming",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_messages
|
||||
WHERE message_id = ${messageId}
|
||||
`,
|
||||
});
|
||||
|
||||
const appendProjectionThreadMessageDeltaRow = SqlSchema.void({
|
||||
Request: AppendProjectionThreadMessageDeltaInput,
|
||||
execute: (row) => {
|
||||
const nextAttachmentsJson =
|
||||
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
|
||||
return sql`
|
||||
INSERT INTO projection_thread_messages (
|
||||
message_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
role,
|
||||
text,
|
||||
attachments_json,
|
||||
is_streaming,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
${row.messageId},
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.role},
|
||||
${row.delta},
|
||||
${nextAttachmentsJson},
|
||||
${row.isStreaming ? 1 : 0},
|
||||
${row.createdAt},
|
||||
${row.updatedAt}
|
||||
)
|
||||
ON CONFLICT (message_id)
|
||||
DO UPDATE SET
|
||||
thread_id = excluded.thread_id,
|
||||
turn_id = COALESCE(excluded.turn_id, projection_thread_messages.turn_id),
|
||||
role = excluded.role,
|
||||
text = projection_thread_messages.text || excluded.text,
|
||||
attachments_json = COALESCE(
|
||||
excluded.attachments_json,
|
||||
projection_thread_messages.attachments_json
|
||||
),
|
||||
is_streaming = excluded.is_streaming,
|
||||
updated_at = excluded.updated_at
|
||||
`;
|
||||
},
|
||||
});
|
||||
|
||||
const deleteProjectionThreadMessageRows = SqlSchema.void({
|
||||
Request: DeleteProjectionThreadMessagesInput,
|
||||
execute: ({ threadId }) =>
|
||||
@@ -114,18 +193,21 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query"),
|
||||
),
|
||||
Effect.map((rows) =>
|
||||
rows.map((row) => ({
|
||||
messageId: row.messageId,
|
||||
threadId: row.threadId,
|
||||
turnId: row.turnId,
|
||||
role: row.role,
|
||||
text: row.text,
|
||||
isStreaming: row.isStreaming === 1,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
...(row.attachments !== null ? { attachments: row.attachments } : {}),
|
||||
})),
|
||||
Effect.map((rows) => rows.map(toProjectionThreadMessage)),
|
||||
);
|
||||
|
||||
const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>
|
||||
getProjectionThreadMessageRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadMessageRepository.getByMessageId:query"),
|
||||
),
|
||||
Effect.map(Option.map(toProjectionThreadMessage)),
|
||||
);
|
||||
|
||||
const appendTextDelta: ProjectionThreadMessageRepositoryShape["appendTextDelta"] = (input) =>
|
||||
appendProjectionThreadMessageDeltaRow(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadMessageRepository.appendTextDelta:query"),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -139,6 +221,8 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
|
||||
return {
|
||||
upsert,
|
||||
listByThreadId,
|
||||
getByMessageId,
|
||||
appendTextDelta,
|
||||
deleteByThreadId,
|
||||
} satisfies ProjectionThreadMessageRepositoryShape;
|
||||
});
|
||||
|
||||
@@ -16,15 +16,14 @@ const defaultSqliteClientLoaders = {
|
||||
node: () => import("../NodeSqliteClient.ts"),
|
||||
} satisfies Record<string, () => Promise<Loader>>;
|
||||
|
||||
const makeRuntimeSqliteLayer = (
|
||||
const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* (
|
||||
config: RuntimeSqliteLayerConfig,
|
||||
): Layer.Layer<SqlClient.SqlClient> =>
|
||||
Effect.gen(function* () {
|
||||
const runtime = process.versions.bun !== undefined ? "bun" : "node";
|
||||
const loader = defaultSqliteClientLoaders[runtime];
|
||||
const clientModule = yield* Effect.promise<Loader>(loader);
|
||||
return clientModule.layer(config);
|
||||
}).pipe(Layer.unwrap);
|
||||
) {
|
||||
const runtime = process.versions.bun !== undefined ? "bun" : "node";
|
||||
const loader = defaultSqliteClientLoaders[runtime];
|
||||
const clientModule = yield* Effect.promise<Loader>(loader);
|
||||
return clientModule.layer(config);
|
||||
}, Layer.unwrap);
|
||||
|
||||
const setup = Layer.effectDiscard(
|
||||
Effect.gen(function* () {
|
||||
@@ -35,14 +34,15 @@ const setup = Layer.effectDiscard(
|
||||
}),
|
||||
);
|
||||
|
||||
export const makeSqlitePersistenceLive = (dbPath: string) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
|
||||
export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* (
|
||||
dbPath: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
|
||||
|
||||
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
|
||||
}).pipe(Layer.unwrap);
|
||||
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
|
||||
}, Layer.unwrap);
|
||||
|
||||
export const SqlitePersistenceMemory = Layer.provideMerge(
|
||||
setup,
|
||||
|
||||
@@ -92,19 +92,20 @@ export interface RunMigrationsOptions {
|
||||
*
|
||||
* @returns Effect containing array of executed migrations
|
||||
*/
|
||||
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.log(
|
||||
toMigrationInclusive === undefined
|
||||
? "Running all migrations..."
|
||||
: `Running migrations 1 through ${toMigrationInclusive}...`,
|
||||
);
|
||||
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
|
||||
yield* Effect.log("Migrations ran successfully").pipe(
|
||||
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
|
||||
);
|
||||
return executedMigrations;
|
||||
});
|
||||
export const runMigrations = Effect.fn("runMigrations")(function* ({
|
||||
toMigrationInclusive,
|
||||
}: RunMigrationsOptions = {}) {
|
||||
yield* Effect.log(
|
||||
toMigrationInclusive === undefined
|
||||
? "Running all migrations..."
|
||||
: `Running migrations 1 through ${toMigrationInclusive}...`,
|
||||
);
|
||||
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
|
||||
yield* Effect.log("Migrations ran successfully").pipe(
|
||||
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
|
||||
);
|
||||
return executedMigrations;
|
||||
});
|
||||
|
||||
/**
|
||||
* Layer that runs migrations when the layer is built.
|
||||
|
||||
@@ -72,160 +72,153 @@ const checkNodeSqliteCompat = () => {
|
||||
return Effect.void;
|
||||
};
|
||||
|
||||
const makeWithDatabase = (
|
||||
const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
|
||||
options: SqliteClientConfig,
|
||||
openDatabase: () => DatabaseSync,
|
||||
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
|
||||
Effect.gen(function* () {
|
||||
yield* checkNodeSqliteCompat();
|
||||
): Effect.fn.Return<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> {
|
||||
yield* checkNodeSqliteCompat();
|
||||
|
||||
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
|
||||
const transformRows = options.transformResultNames
|
||||
? Statement.defaultTransforms(options.transformResultNames).array
|
||||
: undefined;
|
||||
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
|
||||
const transformRows = options.transformResultNames
|
||||
? Statement.defaultTransforms(options.transformResultNames).array
|
||||
: undefined;
|
||||
|
||||
const makeConnection = Effect.gen(function* () {
|
||||
const scope = yield* Effect.scope;
|
||||
const db = openDatabase();
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Effect.sync(() => db.close()),
|
||||
);
|
||||
const makeConnection = Effect.gen(function* () {
|
||||
const scope = yield* Effect.scope;
|
||||
const db = openDatabase();
|
||||
yield* Scope.addFinalizer(
|
||||
scope,
|
||||
Effect.sync(() => db.close()),
|
||||
);
|
||||
|
||||
const statementReaderCache = new WeakMap<StatementSync, boolean>();
|
||||
const hasRows = (statement: StatementSync): boolean => {
|
||||
const cached = statementReaderCache.get(statement);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
const value = statement.columns().length > 0;
|
||||
statementReaderCache.set(statement, value);
|
||||
return value;
|
||||
};
|
||||
const statementReaderCache = new WeakMap<StatementSync, boolean>();
|
||||
const hasRows = (statement: StatementSync): boolean => {
|
||||
const cached = statementReaderCache.get(statement);
|
||||
if (cached !== undefined) {
|
||||
return cached;
|
||||
}
|
||||
const value = statement.columns().length > 0;
|
||||
statementReaderCache.set(statement, value);
|
||||
return value;
|
||||
};
|
||||
|
||||
const prepareCache = yield* Cache.make({
|
||||
capacity: options.prepareCacheSize ?? 200,
|
||||
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
|
||||
lookup: (sql: string) =>
|
||||
Effect.try({
|
||||
try: () => db.prepare(sql),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to prepare statement",
|
||||
operation: "prepare",
|
||||
}),
|
||||
const prepareCache = yield* Cache.make({
|
||||
capacity: options.prepareCacheSize ?? 200,
|
||||
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
|
||||
lookup: (sql: string) =>
|
||||
Effect.try({
|
||||
try: () => db.prepare(sql),
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to prepare statement",
|
||||
operation: "prepare",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
const runStatement = (statement: StatementSync, params: ReadonlyArray<unknown>, raw: boolean) =>
|
||||
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
|
||||
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
|
||||
try {
|
||||
if (hasRows(statement)) {
|
||||
return Effect.succeed(statement.all(...(params as any)));
|
||||
}
|
||||
const result = statement.run(...(params as any));
|
||||
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
|
||||
} catch (cause) {
|
||||
return Effect.fail(
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const runStatement = (
|
||||
statement: StatementSync,
|
||||
params: ReadonlyArray<unknown>,
|
||||
raw: boolean,
|
||||
) =>
|
||||
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
|
||||
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
|
||||
try {
|
||||
if (hasRows(statement)) {
|
||||
return Effect.succeed(statement.all(...(params as any)));
|
||||
}
|
||||
const result = statement.run(...(params as any));
|
||||
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
|
||||
} catch (cause) {
|
||||
return Effect.fail(
|
||||
const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
|
||||
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
|
||||
|
||||
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
|
||||
Effect.acquireUseRelease(
|
||||
Cache.get(prepareCache, sql),
|
||||
(statement) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (hasRows(statement)) {
|
||||
statement.setReturnArrays(true);
|
||||
// Safe to cast to array after we've setReturnArrays(true)
|
||||
return statement.all(...(params as any)) as unknown as ReadonlyArray<
|
||||
ReadonlyArray<unknown>
|
||||
>;
|
||||
}
|
||||
statement.run(...(params as any));
|
||||
return [];
|
||||
},
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
|
||||
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
|
||||
|
||||
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
|
||||
Effect.acquireUseRelease(
|
||||
Cache.get(prepareCache, sql),
|
||||
(statement) =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
if (hasRows(statement)) {
|
||||
statement.setReturnArrays(true);
|
||||
// Safe to cast to array after we've setReturnArrays(true)
|
||||
return statement.all(...(params as any)) as unknown as ReadonlyArray<
|
||||
ReadonlyArray<unknown>
|
||||
>;
|
||||
}
|
||||
statement.run(...(params as any));
|
||||
return [];
|
||||
},
|
||||
catch: (cause) =>
|
||||
new SqlError({
|
||||
reason: classifySqliteError(cause, {
|
||||
message: "Failed to execute statement",
|
||||
operation: "execute",
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
(statement) =>
|
||||
Effect.sync(() => {
|
||||
if (hasRows(statement)) {
|
||||
statement.setReturnArrays(false);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return identity<Connection>({
|
||||
execute(sql, params, rowTransform) {
|
||||
return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
|
||||
},
|
||||
executeRaw(sql, params) {
|
||||
return run(sql, params, true);
|
||||
},
|
||||
executeValues(sql, params) {
|
||||
return runValues(sql, params);
|
||||
},
|
||||
executeUnprepared(sql, params, rowTransform) {
|
||||
const effect = runStatement(db.prepare(sql), params ?? [], false);
|
||||
return rowTransform ? Effect.map(effect, rowTransform) : effect;
|
||||
},
|
||||
executeStream(_sql, _params) {
|
||||
return Stream.die("executeStream not implemented");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const semaphore = yield* Semaphore.make(1);
|
||||
const connection = yield* makeConnection;
|
||||
|
||||
const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
|
||||
const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
|
||||
const fiber = Fiber.getCurrent()!;
|
||||
const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
|
||||
return Effect.as(
|
||||
Effect.tap(restore(semaphore.take(1)), () =>
|
||||
Scope.addFinalizer(scope, semaphore.release(1)),
|
||||
),
|
||||
connection,
|
||||
}),
|
||||
(statement) =>
|
||||
Effect.sync(() => {
|
||||
if (hasRows(statement)) {
|
||||
statement.setReturnArrays(false);
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
return yield* Client.make({
|
||||
acquirer,
|
||||
compiler,
|
||||
transactionAcquirer,
|
||||
spanAttributes: [
|
||||
...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
|
||||
[ATTR_DB_SYSTEM_NAME, "sqlite"],
|
||||
],
|
||||
transformRows,
|
||||
return identity<Connection>({
|
||||
execute(sql, params, rowTransform) {
|
||||
return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
|
||||
},
|
||||
executeRaw(sql, params) {
|
||||
return run(sql, params, true);
|
||||
},
|
||||
executeValues(sql, params) {
|
||||
return runValues(sql, params);
|
||||
},
|
||||
executeUnprepared(sql, params, rowTransform) {
|
||||
const effect = runStatement(db.prepare(sql), params ?? [], false);
|
||||
return rowTransform ? Effect.map(effect, rowTransform) : effect;
|
||||
},
|
||||
executeStream(_sql, _params) {
|
||||
return Stream.die("executeStream not implemented");
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const semaphore = yield* Semaphore.make(1);
|
||||
const connection = yield* makeConnection;
|
||||
|
||||
const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
|
||||
const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
|
||||
const fiber = Fiber.getCurrent()!;
|
||||
const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
|
||||
return Effect.as(
|
||||
Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))),
|
||||
connection,
|
||||
);
|
||||
});
|
||||
|
||||
return yield* Client.make({
|
||||
acquirer,
|
||||
compiler,
|
||||
transactionAcquirer,
|
||||
spanAttributes: [
|
||||
...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
|
||||
[ATTR_DB_SYSTEM_NAME, "sqlite"],
|
||||
],
|
||||
transformRows,
|
||||
});
|
||||
});
|
||||
|
||||
const make = (
|
||||
options: SqliteClientConfig,
|
||||
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
TurnId,
|
||||
IsoDateTime,
|
||||
} from "@t3tools/contracts";
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import { Option, Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../Errors.ts";
|
||||
@@ -37,11 +37,30 @@ export const ListProjectionThreadMessagesInput = Schema.Struct({
|
||||
});
|
||||
export type ListProjectionThreadMessagesInput = typeof ListProjectionThreadMessagesInput.Type;
|
||||
|
||||
export const GetProjectionThreadMessageInput = Schema.Struct({
|
||||
messageId: MessageId,
|
||||
});
|
||||
export type GetProjectionThreadMessageInput = typeof GetProjectionThreadMessageInput.Type;
|
||||
|
||||
export const DeleteProjectionThreadMessagesInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type DeleteProjectionThreadMessagesInput = typeof DeleteProjectionThreadMessagesInput.Type;
|
||||
|
||||
export const AppendProjectionThreadMessageDeltaInput = Schema.Struct({
|
||||
messageId: MessageId,
|
||||
threadId: ThreadId,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
role: OrchestrationMessageRole,
|
||||
delta: Schema.String,
|
||||
attachments: Schema.optional(Schema.Array(ChatAttachment)),
|
||||
isStreaming: Schema.Boolean,
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type AppendProjectionThreadMessageDeltaInput =
|
||||
typeof AppendProjectionThreadMessageDeltaInput.Type;
|
||||
|
||||
/**
|
||||
* ProjectionThreadMessageRepositoryShape - Service API for projected thread messages.
|
||||
*/
|
||||
@@ -64,6 +83,20 @@ export interface ProjectionThreadMessageRepositoryShape {
|
||||
input: ListProjectionThreadMessagesInput,
|
||||
) => Effect.Effect<ReadonlyArray<ProjectionThreadMessage>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Look up a projected message by id.
|
||||
*/
|
||||
readonly getByMessageId: (
|
||||
input: GetProjectionThreadMessageInput,
|
||||
) => Effect.Effect<Option.Option<ProjectionThreadMessage>, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Append a streaming text delta to an existing projected message row, or insert it.
|
||||
*/
|
||||
readonly appendTextDelta: (
|
||||
input: AppendProjectionThreadMessageDeltaInput,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Delete projected thread messages by thread.
|
||||
*/
|
||||
|
||||
@@ -3054,7 +3054,9 @@ const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEventQueue),
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEventQueue);
|
||||
},
|
||||
} satisfies ClaudeAdapterShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -427,17 +427,16 @@ const probeClaudeCapabilities = (binaryPath: string) => {
|
||||
);
|
||||
};
|
||||
|
||||
const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
);
|
||||
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
|
||||
const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: ReadonlyArray<string>) {
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
Effect.flatMap((service) => service.getSettings),
|
||||
Effect.map((settings) => settings.providers.claudeAgent),
|
||||
);
|
||||
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
|
||||
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
|
||||
|
||||
@@ -1631,7 +1631,9 @@ const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
listSessions,
|
||||
hasSession,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEventQueue),
|
||||
get streamEvents() {
|
||||
return Stream.fromQueue(runtimeEventQueue);
|
||||
},
|
||||
} satisfies CodexAdapterShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -306,21 +306,20 @@ const probeCodexCapabilities = (input: {
|
||||
}),
|
||||
);
|
||||
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
const codexSettings = yield* settingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
);
|
||||
const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
|
||||
shell: process.platform === "win32",
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
});
|
||||
return yield* spawnAndCollect(codexSettings.binaryPath, command);
|
||||
const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray<string>) {
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
const codexSettings = yield* settingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.providers.codex),
|
||||
);
|
||||
const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
|
||||
shell: process.platform === "win32",
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
});
|
||||
return yield* spawnAndCollect(codexSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
|
||||
resolveAccount?: (input: {
|
||||
|
||||
@@ -74,184 +74,180 @@ function resolveStreamLabel(stream: EventNdjsonStream): string {
|
||||
}
|
||||
}
|
||||
|
||||
function toLogMessage(event: unknown): Effect.Effect<string | undefined> {
|
||||
return Effect.gen(function* () {
|
||||
const serialized = yield* Effect.sync(() => {
|
||||
try {
|
||||
return { ok: true as const, value: JSON.stringify(event) };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!serialized.ok) {
|
||||
yield* logWarning("failed to serialize provider event log record", {
|
||||
error: serialized.error,
|
||||
});
|
||||
return undefined;
|
||||
const toLogMessage = Effect.fn("toLogMessage")(function* (
|
||||
event: unknown,
|
||||
): Effect.fn.Return<string | undefined> {
|
||||
const serialized = yield* Effect.sync(() => {
|
||||
try {
|
||||
return { ok: true as const, value: JSON.stringify(event) };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
|
||||
if (typeof serialized.value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return serialized.value;
|
||||
});
|
||||
}
|
||||
|
||||
function makeThreadWriter(input: {
|
||||
if (!serialized.ok) {
|
||||
yield* logWarning("failed to serialize provider event log record", {
|
||||
error: serialized.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (typeof serialized.value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return serialized.value;
|
||||
});
|
||||
|
||||
const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
|
||||
readonly filePath: string;
|
||||
readonly maxBytes: number;
|
||||
readonly maxFiles: number;
|
||||
readonly batchWindowMs: number;
|
||||
readonly streamLabel: string;
|
||||
}): Effect.Effect<ThreadWriter | undefined> {
|
||||
return Effect.gen(function* () {
|
||||
const sinkResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
return {
|
||||
ok: true as const,
|
||||
sink: new RotatingFileSink({
|
||||
filePath: input.filePath,
|
||||
maxBytes: input.maxBytes,
|
||||
maxFiles: input.maxFiles,
|
||||
throwOnError: true,
|
||||
}),
|
||||
};
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!sinkResult.ok) {
|
||||
yield* logWarning("failed to initialize provider thread log file", {
|
||||
filePath: input.filePath,
|
||||
error: sinkResult.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sink = sinkResult.sink;
|
||||
const scope = yield* Scope.make();
|
||||
const lineLogger = makeLineLogger(input.streamLabel);
|
||||
const batchedLogger = yield* Logger.batched(lineLogger, {
|
||||
window: input.batchWindowMs,
|
||||
flush: (messages) =>
|
||||
Effect.gen(function* () {
|
||||
const flushResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
for (const message of messages) {
|
||||
sink.write(message);
|
||||
}
|
||||
return { ok: true as const };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!flushResult.ok) {
|
||||
yield* logWarning("provider event log batch flush failed", {
|
||||
filePath: input.filePath,
|
||||
error: flushResult.error,
|
||||
});
|
||||
}
|
||||
}): Effect.fn.Return<ThreadWriter | undefined> {
|
||||
const sinkResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
return {
|
||||
ok: true as const,
|
||||
sink: new RotatingFileSink({
|
||||
filePath: input.filePath,
|
||||
maxBytes: input.maxBytes,
|
||||
maxFiles: input.maxFiles,
|
||||
throwOnError: true,
|
||||
}),
|
||||
}).pipe(Effect.provideService(Scope.Scope, scope));
|
||||
|
||||
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
|
||||
|
||||
return {
|
||||
writeMessage(message: string) {
|
||||
return Effect.log(message).pipe(Effect.provide(loggerLayer));
|
||||
},
|
||||
close() {
|
||||
return Scope.close(scope, Exit.void);
|
||||
},
|
||||
} satisfies ThreadWriter;
|
||||
};
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function makeEventNdjsonLogger(
|
||||
if (!sinkResult.ok) {
|
||||
yield* logWarning("failed to initialize provider thread log file", {
|
||||
filePath: input.filePath,
|
||||
error: sinkResult.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const sink = sinkResult.sink;
|
||||
const scope = yield* Scope.make();
|
||||
const lineLogger = makeLineLogger(input.streamLabel);
|
||||
const batchedLogger = yield* Logger.batched(lineLogger, {
|
||||
window: input.batchWindowMs,
|
||||
flush: Effect.fn("makeThreadWriter.flush")(function* (messages) {
|
||||
const flushResult = yield* Effect.sync(() => {
|
||||
try {
|
||||
for (const message of messages) {
|
||||
sink.write(message);
|
||||
}
|
||||
return { ok: true as const };
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
|
||||
if (!flushResult.ok) {
|
||||
yield* logWarning("provider event log batch flush failed", {
|
||||
filePath: input.filePath,
|
||||
error: flushResult.error,
|
||||
});
|
||||
}
|
||||
}),
|
||||
}).pipe(Effect.provideService(Scope.Scope, scope));
|
||||
|
||||
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
|
||||
|
||||
return {
|
||||
writeMessage(message: string) {
|
||||
return Effect.log(message).pipe(Effect.provide(loggerLayer));
|
||||
},
|
||||
close() {
|
||||
return Scope.close(scope, Exit.void);
|
||||
},
|
||||
} satisfies ThreadWriter;
|
||||
});
|
||||
|
||||
export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
|
||||
filePath: string,
|
||||
options: EventNdjsonLoggerOptions,
|
||||
): Effect.Effect<EventNdjsonLogger | undefined> {
|
||||
return Effect.gen(function* () {
|
||||
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
||||
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
|
||||
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
|
||||
const streamLabel = resolveStreamLabel(options.stream);
|
||||
): Effect.fn.Return<EventNdjsonLogger | undefined> {
|
||||
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
||||
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
|
||||
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
|
||||
const streamLabel = resolveStreamLabel(options.stream);
|
||||
|
||||
const directoryReady = yield* Effect.sync(() => {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
return true;
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
const directoryReady = yield* Effect.sync(() => {
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
return true;
|
||||
} catch (error) {
|
||||
return { ok: false as const, error };
|
||||
}
|
||||
});
|
||||
if (directoryReady !== true) {
|
||||
yield* logWarning("failed to create provider event log directory", {
|
||||
filePath,
|
||||
error: directoryReady.error,
|
||||
});
|
||||
if (directoryReady !== true) {
|
||||
yield* logWarning("failed to create provider event log directory", {
|
||||
filePath,
|
||||
error: directoryReady.error,
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const threadWriters = new Map<string, ThreadWriter>();
|
||||
const failedSegments = new Set<string>();
|
||||
|
||||
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
|
||||
threadSegment: string,
|
||||
): Effect.fn.Return<ThreadWriter | undefined> {
|
||||
if (failedSegments.has(threadSegment)) {
|
||||
return undefined;
|
||||
}
|
||||
const existing = threadWriters.get(threadSegment);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const writer = yield* makeThreadWriter({
|
||||
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
|
||||
maxBytes,
|
||||
maxFiles,
|
||||
batchWindowMs,
|
||||
streamLabel,
|
||||
});
|
||||
if (!writer) {
|
||||
failedSegments.add(threadSegment);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const threadWriters = new Map<string, ThreadWriter>();
|
||||
const failedSegments = new Set<string>();
|
||||
|
||||
const resolveThreadWriter = (threadSegment: string): Effect.Effect<ThreadWriter | undefined> =>
|
||||
Effect.gen(function* () {
|
||||
if (failedSegments.has(threadSegment)) {
|
||||
return undefined;
|
||||
}
|
||||
const existing = threadWriters.get(threadSegment);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const writer = yield* makeThreadWriter({
|
||||
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
|
||||
maxBytes,
|
||||
maxFiles,
|
||||
batchWindowMs,
|
||||
streamLabel,
|
||||
});
|
||||
if (!writer) {
|
||||
failedSegments.add(threadSegment);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
threadWriters.set(threadSegment, writer);
|
||||
return writer;
|
||||
});
|
||||
|
||||
return {
|
||||
filePath,
|
||||
write(event: unknown, threadId: ThreadId | null) {
|
||||
return Effect.gen(function* () {
|
||||
const threadSegment = resolveThreadSegment(threadId);
|
||||
const message = yield* toLogMessage(event);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
const writer = yield* resolveThreadWriter(threadSegment);
|
||||
if (!writer) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writer.writeMessage(message);
|
||||
});
|
||||
},
|
||||
close() {
|
||||
return Effect.gen(function* () {
|
||||
for (const writer of threadWriters.values()) {
|
||||
yield* writer.close();
|
||||
}
|
||||
threadWriters.clear();
|
||||
});
|
||||
},
|
||||
} satisfies EventNdjsonLogger;
|
||||
threadWriters.set(threadSegment, writer);
|
||||
return writer;
|
||||
});
|
||||
}
|
||||
|
||||
const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
|
||||
const threadSegment = resolveThreadSegment(threadId);
|
||||
const message = yield* toLogMessage(event);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
const writer = yield* resolveThreadWriter(threadSegment);
|
||||
if (!writer) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* writer.writeMessage(message);
|
||||
});
|
||||
|
||||
const close = Effect.fn("close")(function* () {
|
||||
for (const writer of threadWriters.values()) {
|
||||
yield* writer.close();
|
||||
}
|
||||
threadWriters.clear();
|
||||
});
|
||||
|
||||
return {
|
||||
filePath,
|
||||
write,
|
||||
close,
|
||||
} satisfies EventNdjsonLogger;
|
||||
});
|
||||
@@ -22,30 +22,31 @@ export interface ProviderAdapterRegistryLiveOptions {
|
||||
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
|
||||
}
|
||||
|
||||
const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: [yield* CodexAdapter, yield* ClaudeAdapter];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (
|
||||
options?: ProviderAdapterRegistryLiveOptions,
|
||||
) {
|
||||
const adapters =
|
||||
options?.adapters !== undefined
|
||||
? options.adapters
|
||||
: [yield* CodexAdapter, yield* ClaudeAdapter];
|
||||
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
|
||||
|
||||
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
|
||||
const adapter = byProvider.get(provider);
|
||||
if (!adapter) {
|
||||
return Effect.fail(new ProviderUnsupportedError({ provider }));
|
||||
}
|
||||
return Effect.succeed(adapter);
|
||||
};
|
||||
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
|
||||
const adapter = byProvider.get(provider);
|
||||
if (!adapter) {
|
||||
return Effect.fail(new ProviderUnsupportedError({ provider }));
|
||||
}
|
||||
return Effect.succeed(adapter);
|
||||
};
|
||||
|
||||
const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
|
||||
Effect.sync(() => Array.from(byProvider.keys()));
|
||||
const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
|
||||
Effect.sync(() => Array.from(byProvider.keys()));
|
||||
|
||||
return {
|
||||
getByProvider,
|
||||
listProviders,
|
||||
} satisfies ProviderAdapterRegistryShape;
|
||||
});
|
||||
return {
|
||||
getByProvider,
|
||||
listProviders,
|
||||
} satisfies ProviderAdapterRegistryShape;
|
||||
});
|
||||
|
||||
export const ProviderAdapterRegistryLive = Layer.effect(
|
||||
ProviderAdapterRegistry,
|
||||
|
||||
@@ -115,7 +115,9 @@ function makeMutableServerSettingsService(
|
||||
yield* PubSub.publish(changes, next);
|
||||
return next;
|
||||
}),
|
||||
streamChanges: Stream.fromPubSub(changes),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changes);
|
||||
},
|
||||
} satisfies ServerSettingsShape;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -40,18 +40,19 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
yield* loadProviders(codexProvider, claudeProvider),
|
||||
);
|
||||
|
||||
const syncProviders = (options?: { readonly publish?: boolean }) =>
|
||||
Effect.gen(function* () {
|
||||
const previousProviders = yield* Ref.get(providersRef);
|
||||
const providers = yield* loadProviders(codexProvider, claudeProvider);
|
||||
yield* Ref.set(providersRef, providers);
|
||||
const syncProviders = Effect.fn("syncProviders")(function* (options?: {
|
||||
readonly publish?: boolean;
|
||||
}) {
|
||||
const previousProviders = yield* Ref.get(providersRef);
|
||||
const providers = yield* loadProviders(codexProvider, claudeProvider);
|
||||
yield* Ref.set(providersRef, providers);
|
||||
|
||||
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
|
||||
yield* PubSub.publish(changesPubSub, providers);
|
||||
}
|
||||
|
||||
return providers;
|
||||
});
|
||||
return providers;
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe(
|
||||
Effect.forkScoped,
|
||||
@@ -60,28 +61,30 @@ export const ProviderRegistryLive = Layer.effect(
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const refresh = Effect.fn("refresh")(function* (provider?: ProviderKind) {
|
||||
switch (provider) {
|
||||
case "codex":
|
||||
yield* codexProvider.refresh;
|
||||
break;
|
||||
case "claudeAgent":
|
||||
yield* claudeProvider.refresh;
|
||||
break;
|
||||
default:
|
||||
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
break;
|
||||
}
|
||||
return yield* syncProviders();
|
||||
});
|
||||
|
||||
return {
|
||||
getProviders: syncProviders({ publish: false }).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
refresh: (provider?: ProviderKind) =>
|
||||
Effect.gen(function* () {
|
||||
switch (provider) {
|
||||
case "codex":
|
||||
yield* codexProvider.refresh;
|
||||
break;
|
||||
case "claudeAgent":
|
||||
yield* claudeProvider.refresh;
|
||||
break;
|
||||
default:
|
||||
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
|
||||
concurrency: "unbounded",
|
||||
});
|
||||
break;
|
||||
}
|
||||
return yield* syncProviders();
|
||||
}).pipe(
|
||||
refresh(provider).pipe(
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orElseSucceed(() => []),
|
||||
),
|
||||
|
||||
@@ -191,7 +191,9 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
|
||||
readThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
get streamEvents() {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
};
|
||||
|
||||
const emit = (event: LegacyProviderRuntimeEvent): void => {
|
||||
|
||||
@@ -131,472 +131,470 @@ function readPersistedCwd(
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}
|
||||
|
||||
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const analytics = yield* Effect.service(AnalyticsService);
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const canonicalEventLogger =
|
||||
options?.canonicalEventLogger ??
|
||||
(options?.canonicalEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
|
||||
stream: "canonical",
|
||||
})
|
||||
: undefined);
|
||||
const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
options?: ProviderServiceLiveOptions,
|
||||
) {
|
||||
const analytics = yield* Effect.service(AnalyticsService);
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const canonicalEventLogger =
|
||||
options?.canonicalEventLogger ??
|
||||
(options?.canonicalEventLogPath !== undefined
|
||||
? yield* makeEventNdjsonLogger(options.canonicalEventLogPath, {
|
||||
stream: "canonical",
|
||||
})
|
||||
: undefined);
|
||||
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
const registry = yield* ProviderAdapterRegistry;
|
||||
const directory = yield* ProviderSessionDirectory;
|
||||
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>();
|
||||
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
Effect.succeed(event).pipe(
|
||||
Effect.tap((canonicalEvent) =>
|
||||
canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
|
||||
),
|
||||
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
const upsertSessionBinding = (
|
||||
session: ProviderSession,
|
||||
threadId: ThreadId,
|
||||
extra?: {
|
||||
readonly modelSelection?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
provider: session.provider,
|
||||
runtimeMode: session.runtimeMode,
|
||||
status: toRuntimeStatus(session),
|
||||
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
|
||||
runtimePayload: toRuntimePayloadFromSession(session, extra),
|
||||
});
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
const adapters = yield* Effect.forEach(providers, (provider) =>
|
||||
registry.getByProvider(provider),
|
||||
);
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
publishRuntimeEvent(event);
|
||||
|
||||
const worker = Effect.forever(
|
||||
Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
|
||||
);
|
||||
yield* Effect.forkScoped(worker);
|
||||
|
||||
yield* Effect.forEach(adapters, (adapter) =>
|
||||
Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkScoped),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const recoverSessionForThread = (input: {
|
||||
readonly binding: ProviderRuntimeBinding;
|
||||
readonly operation: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* registry.getByProvider(input.binding.provider);
|
||||
const hasResumeCursor =
|
||||
input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
|
||||
const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
|
||||
if (hasActiveSession) {
|
||||
const activeSessions = yield* adapter.listSessions();
|
||||
const existing = activeSessions.find(
|
||||
(session) => session.threadId === input.binding.threadId,
|
||||
);
|
||||
if (existing) {
|
||||
yield* upsertSessionBinding(existing, input.binding.threadId);
|
||||
yield* analytics.record("provider.session.recovered", {
|
||||
provider: existing.provider,
|
||||
strategy: "adopt-existing",
|
||||
hasResumeCursor: existing.resumeCursor !== undefined,
|
||||
});
|
||||
return { adapter, session: existing } as const;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasResumeCursor) {
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
|
||||
);
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
|
||||
|
||||
const resumed = yield* adapter.startSession({
|
||||
threadId: input.binding.threadId,
|
||||
provider: input.binding.provider,
|
||||
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
runtimeMode: input.binding.runtimeMode ?? "full-access",
|
||||
});
|
||||
if (resumed.provider !== adapter.provider) {
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(resumed, input.binding.threadId);
|
||||
yield* analytics.record("provider.session.recovered", {
|
||||
provider: resumed.provider,
|
||||
strategy: "resume-thread",
|
||||
hasResumeCursor: resumed.resumeCursor !== undefined,
|
||||
});
|
||||
return { adapter, session: resumed } as const;
|
||||
});
|
||||
|
||||
const resolveRoutableSession = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly operation: string;
|
||||
readonly allowRecovery: boolean;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const bindingOption = yield* directory.getBinding(input.threadId);
|
||||
const binding = Option.getOrUndefined(bindingOption);
|
||||
if (!binding) {
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
|
||||
);
|
||||
}
|
||||
const adapter = yield* registry.getByProvider(binding.provider);
|
||||
|
||||
const hasRequestedSession = yield* adapter.hasSession(input.threadId);
|
||||
if (hasRequestedSession) {
|
||||
return { adapter, threadId: input.threadId, isActive: true } as const;
|
||||
}
|
||||
|
||||
if (!input.allowRecovery) {
|
||||
return { adapter, threadId: input.threadId, isActive: false } as const;
|
||||
}
|
||||
|
||||
const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
|
||||
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
|
||||
});
|
||||
|
||||
const startSession: ProviderServiceShape["startSession"] = (threadId, rawInput) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
schema: ProviderSessionStartInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
|
||||
const input = {
|
||||
...parsed,
|
||||
threadId,
|
||||
provider: parsed.provider ?? "codex",
|
||||
};
|
||||
const settings = yield* serverSettings.getSettings.pipe(
|
||||
Effect.mapError((error) =>
|
||||
toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Failed to load provider settings: ${error.message}`,
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!settings.providers[input.provider].enabled) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Provider '${input.provider}' is disabled in T3 Code settings.`,
|
||||
);
|
||||
}
|
||||
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
|
||||
const effectiveResumeCursor =
|
||||
input.resumeCursor ??
|
||||
(persistedBinding?.provider === input.provider
|
||||
? persistedBinding.resumeCursor
|
||||
: undefined);
|
||||
const adapter = yield* registry.getByProvider(input.provider);
|
||||
const session = yield* adapter.startSession({
|
||||
...input,
|
||||
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
|
||||
});
|
||||
|
||||
if (session.provider !== adapter.provider) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
yield* analytics.record("provider.session.started", {
|
||||
provider: session.provider,
|
||||
runtimeMode: input.runtimeMode,
|
||||
hasResumeCursor: session.resumeCursor !== undefined,
|
||||
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
|
||||
hasModel:
|
||||
typeof input.modelSelection?.model === "string" &&
|
||||
input.modelSelection.model.trim().length > 0,
|
||||
});
|
||||
|
||||
return session;
|
||||
});
|
||||
|
||||
const sendTurn: ProviderServiceShape["sendTurn"] = (rawInput) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.sendTurn",
|
||||
schema: ProviderSendTurnInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
|
||||
const input = {
|
||||
...parsed,
|
||||
attachments: parsed.attachments ?? [],
|
||||
};
|
||||
if (!input.input && input.attachments.length === 0) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.sendTurn",
|
||||
"Either input text or at least one attachment is required",
|
||||
);
|
||||
}
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.sendTurn",
|
||||
allowRecovery: true,
|
||||
});
|
||||
const turn = yield* routed.adapter.sendTurn(input);
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
provider: routed.adapter.provider,
|
||||
status: "running",
|
||||
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
|
||||
runtimePayload: {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
activeTurnId: turn.turnId,
|
||||
lastRuntimeEvent: "provider.sendTurn",
|
||||
lastRuntimeEventAt: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
yield* analytics.record("provider.turn.sent", {
|
||||
provider: routed.adapter.provider,
|
||||
model: input.modelSelection?.model,
|
||||
interactionMode: input.interactionMode,
|
||||
attachmentCount: input.attachments.length,
|
||||
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
|
||||
});
|
||||
return turn;
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderServiceShape["interruptTurn"] = (rawInput) =>
|
||||
Effect.gen(function* () {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.interruptTurn",
|
||||
schema: ProviderInterruptTurnInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.interruptTurn",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
|
||||
yield* analytics.record("provider.turn.interrupted", {
|
||||
provider: routed.adapter.provider,
|
||||
});
|
||||
});
|
||||
|
||||
const respondToRequest: ProviderServiceShape["respondToRequest"] = (rawInput) =>
|
||||
Effect.gen(function* () {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.respondToRequest",
|
||||
schema: ProviderRespondToRequestInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.respondToRequest",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
|
||||
yield* analytics.record("provider.request.responded", {
|
||||
provider: routed.adapter.provider,
|
||||
decision: input.decision,
|
||||
});
|
||||
});
|
||||
|
||||
const respondToUserInput: ProviderServiceShape["respondToUserInput"] = (rawInput) =>
|
||||
Effect.gen(function* () {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.respondToUserInput",
|
||||
schema: ProviderRespondToUserInputInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.respondToUserInput",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
|
||||
});
|
||||
|
||||
const stopSession: ProviderServiceShape["stopSession"] = (rawInput) =>
|
||||
Effect.gen(function* () {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.stopSession",
|
||||
schema: ProviderStopSessionInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.stopSession",
|
||||
allowRecovery: false,
|
||||
});
|
||||
if (routed.isActive) {
|
||||
yield* routed.adapter.stopSession(routed.threadId);
|
||||
}
|
||||
yield* directory.remove(input.threadId);
|
||||
yield* analytics.record("provider.session.stopped", {
|
||||
provider: routed.adapter.provider,
|
||||
});
|
||||
});
|
||||
|
||||
const listSessions: ProviderServiceShape["listSessions"] = () =>
|
||||
Effect.gen(function* () {
|
||||
const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
|
||||
adapter.listSessions(),
|
||||
);
|
||||
const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
|
||||
const persistedBindings = yield* directory.listThreadIds().pipe(
|
||||
Effect.flatMap((threadIds) =>
|
||||
Effect.forEach(
|
||||
threadIds,
|
||||
(threadId) =>
|
||||
directory
|
||||
.getBinding(threadId)
|
||||
.pipe(Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>())),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
|
||||
);
|
||||
const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
|
||||
for (const bindingOption of persistedBindings) {
|
||||
const binding = Option.getOrUndefined(bindingOption);
|
||||
if (binding) {
|
||||
bindingsByThreadId.set(binding.threadId, binding);
|
||||
}
|
||||
}
|
||||
|
||||
return activeSessions.map((session) => {
|
||||
const binding = bindingsByThreadId.get(session.threadId);
|
||||
if (!binding) {
|
||||
return session;
|
||||
}
|
||||
|
||||
const overrides: {
|
||||
resumeCursor?: ProviderSession["resumeCursor"];
|
||||
runtimeMode?: ProviderSession["runtimeMode"];
|
||||
} = {};
|
||||
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
|
||||
overrides.resumeCursor = binding.resumeCursor;
|
||||
}
|
||||
if (binding.runtimeMode !== undefined) {
|
||||
overrides.runtimeMode = binding.runtimeMode;
|
||||
}
|
||||
return Object.assign({}, session, overrides);
|
||||
});
|
||||
});
|
||||
|
||||
const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>
|
||||
registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));
|
||||
|
||||
const rollbackConversation: ProviderServiceShape["rollbackConversation"] = (rawInput) =>
|
||||
Effect.gen(function* () {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.rollbackConversation",
|
||||
schema: ProviderRollbackConversationInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
if (input.numTurns === 0) {
|
||||
return;
|
||||
}
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.rollbackConversation",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
|
||||
yield* analytics.record("provider.conversation.rolled_back", {
|
||||
provider: routed.adapter.provider,
|
||||
turns: input.numTurns,
|
||||
});
|
||||
});
|
||||
|
||||
const runStopAll = () =>
|
||||
Effect.gen(function* () {
|
||||
const threadIds = yield* directory.listThreadIds();
|
||||
const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
|
||||
adapter.listSessions(),
|
||||
).pipe(
|
||||
Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)),
|
||||
);
|
||||
yield* Effect.forEach(activeSessions, (session) =>
|
||||
upsertSessionBinding(session, session.threadId, {
|
||||
lastRuntimeEvent: "provider.stopAll",
|
||||
lastRuntimeEventAt: new Date().toISOString(),
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
|
||||
yield* Effect.forEach(threadIds, (threadId) =>
|
||||
directory.getProvider(threadId).pipe(
|
||||
Effect.flatMap((provider) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
provider,
|
||||
status: "stopped",
|
||||
runtimePayload: {
|
||||
activeTurnId: null,
|
||||
lastRuntimeEvent: "provider.stopAll",
|
||||
lastRuntimeEventAt: new Date().toISOString(),
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.asVoid);
|
||||
yield* analytics.record("provider.sessions.stopped_all", {
|
||||
sessionCount: threadIds.length,
|
||||
});
|
||||
yield* analytics.flush;
|
||||
});
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.catch(runStopAll(), (cause) =>
|
||||
Effect.logWarning("failed to stop provider service", { cause }),
|
||||
const publishRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
Effect.succeed(event).pipe(
|
||||
Effect.tap((canonicalEvent) =>
|
||||
canonicalEventLogger ? canonicalEventLogger.write(canonicalEvent, null) : Effect.void,
|
||||
),
|
||||
Effect.flatMap((canonicalEvent) => PubSub.publish(runtimeEventPubSub, canonicalEvent)),
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
return {
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
getCapabilities,
|
||||
rollbackConversation,
|
||||
// Each access creates a fresh PubSub subscription so that multiple
|
||||
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
|
||||
// independently receive all runtime events.
|
||||
get streamEvents(): ProviderServiceShape["streamEvents"] {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
} satisfies ProviderServiceShape;
|
||||
const upsertSessionBinding = (
|
||||
session: ProviderSession,
|
||||
threadId: ThreadId,
|
||||
extra?: {
|
||||
readonly modelSelection?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
provider: session.provider,
|
||||
runtimeMode: session.runtimeMode,
|
||||
status: toRuntimeStatus(session),
|
||||
...(session.resumeCursor !== undefined ? { resumeCursor: session.resumeCursor } : {}),
|
||||
runtimePayload: toRuntimePayloadFromSession(session, extra),
|
||||
});
|
||||
|
||||
const providers = yield* registry.listProviders();
|
||||
const adapters = yield* Effect.forEach(providers, (provider) => registry.getByProvider(provider));
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
|
||||
publishRuntimeEvent(event);
|
||||
|
||||
const worker = Effect.forever(
|
||||
Queue.take(runtimeEventQueue).pipe(Effect.flatMap(processRuntimeEvent)),
|
||||
);
|
||||
yield* Effect.forkScoped(worker);
|
||||
|
||||
yield* Effect.forEach(adapters, (adapter) =>
|
||||
Stream.runForEach(adapter.streamEvents, (event) =>
|
||||
Queue.offer(runtimeEventQueue, event).pipe(Effect.asVoid),
|
||||
).pipe(Effect.forkScoped),
|
||||
).pipe(Effect.asVoid);
|
||||
|
||||
const recoverSessionForThread = Effect.fn("recoverSessionForThread")(function* (input: {
|
||||
readonly binding: ProviderRuntimeBinding;
|
||||
readonly operation: string;
|
||||
}) {
|
||||
const adapter = yield* registry.getByProvider(input.binding.provider);
|
||||
const hasResumeCursor =
|
||||
input.binding.resumeCursor !== null && input.binding.resumeCursor !== undefined;
|
||||
const hasActiveSession = yield* adapter.hasSession(input.binding.threadId);
|
||||
if (hasActiveSession) {
|
||||
const activeSessions = yield* adapter.listSessions();
|
||||
const existing = activeSessions.find(
|
||||
(session) => session.threadId === input.binding.threadId,
|
||||
);
|
||||
if (existing) {
|
||||
yield* upsertSessionBinding(existing, input.binding.threadId);
|
||||
yield* analytics.record("provider.session.recovered", {
|
||||
provider: existing.provider,
|
||||
strategy: "adopt-existing",
|
||||
hasResumeCursor: existing.resumeCursor !== undefined,
|
||||
});
|
||||
return { adapter, session: existing } as const;
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasResumeCursor) {
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Cannot recover thread '${input.binding.threadId}' because no provider resume state is persisted.`,
|
||||
);
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
|
||||
|
||||
const resumed = yield* adapter.startSession({
|
||||
threadId: input.binding.threadId,
|
||||
provider: input.binding.provider,
|
||||
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
runtimeMode: input.binding.runtimeMode ?? "full-access",
|
||||
});
|
||||
if (resumed.provider !== adapter.provider) {
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Adapter/provider mismatch while recovering thread '${input.binding.threadId}'. Expected '${adapter.provider}', received '${resumed.provider}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(resumed, input.binding.threadId);
|
||||
yield* analytics.record("provider.session.recovered", {
|
||||
provider: resumed.provider,
|
||||
strategy: "resume-thread",
|
||||
hasResumeCursor: resumed.resumeCursor !== undefined,
|
||||
});
|
||||
return { adapter, session: resumed } as const;
|
||||
});
|
||||
|
||||
const resolveRoutableSession = Effect.fn("resolveRoutableSession")(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly operation: string;
|
||||
readonly allowRecovery: boolean;
|
||||
}) {
|
||||
const bindingOption = yield* directory.getBinding(input.threadId);
|
||||
const binding = Option.getOrUndefined(bindingOption);
|
||||
if (!binding) {
|
||||
return yield* toValidationError(
|
||||
input.operation,
|
||||
`Cannot route thread '${input.threadId}' because no persisted provider binding exists.`,
|
||||
);
|
||||
}
|
||||
const adapter = yield* registry.getByProvider(binding.provider);
|
||||
|
||||
const hasRequestedSession = yield* adapter.hasSession(input.threadId);
|
||||
if (hasRequestedSession) {
|
||||
return { adapter, threadId: input.threadId, isActive: true } as const;
|
||||
}
|
||||
|
||||
if (!input.allowRecovery) {
|
||||
return { adapter, threadId: input.threadId, isActive: false } as const;
|
||||
}
|
||||
|
||||
const recovered = yield* recoverSessionForThread({ binding, operation: input.operation });
|
||||
return { adapter: recovered.adapter, threadId: input.threadId, isActive: true } as const;
|
||||
});
|
||||
|
||||
const startSession: ProviderServiceShape["startSession"] = Effect.fn("startSession")(
|
||||
function* (threadId, rawInput) {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.startSession",
|
||||
schema: ProviderSessionStartInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
|
||||
const input = {
|
||||
...parsed,
|
||||
threadId,
|
||||
provider: parsed.provider ?? "codex",
|
||||
};
|
||||
const settings = yield* serverSettings.getSettings.pipe(
|
||||
Effect.mapError((error) =>
|
||||
toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Failed to load provider settings: ${error.message}`,
|
||||
error,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!settings.providers[input.provider].enabled) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Provider '${input.provider}' is disabled in T3 Code settings.`,
|
||||
);
|
||||
}
|
||||
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
|
||||
const effectiveResumeCursor =
|
||||
input.resumeCursor ??
|
||||
(persistedBinding?.provider === input.provider ? persistedBinding.resumeCursor : undefined);
|
||||
const adapter = yield* registry.getByProvider(input.provider);
|
||||
const session = yield* adapter.startSession({
|
||||
...input,
|
||||
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
|
||||
});
|
||||
|
||||
if (session.provider !== adapter.provider) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.startSession",
|
||||
`Adapter/provider mismatch: requested '${adapter.provider}', received '${session.provider}'.`,
|
||||
);
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
yield* analytics.record("provider.session.started", {
|
||||
provider: session.provider,
|
||||
runtimeMode: input.runtimeMode,
|
||||
hasResumeCursor: session.resumeCursor !== undefined,
|
||||
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
|
||||
hasModel:
|
||||
typeof input.modelSelection?.model === "string" &&
|
||||
input.modelSelection.model.trim().length > 0,
|
||||
});
|
||||
|
||||
return session;
|
||||
},
|
||||
);
|
||||
|
||||
const sendTurn: ProviderServiceShape["sendTurn"] = Effect.fn("sendTurn")(function* (rawInput) {
|
||||
const parsed = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.sendTurn",
|
||||
schema: ProviderSendTurnInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
|
||||
const input = {
|
||||
...parsed,
|
||||
attachments: parsed.attachments ?? [],
|
||||
};
|
||||
if (!input.input && input.attachments.length === 0) {
|
||||
return yield* toValidationError(
|
||||
"ProviderService.sendTurn",
|
||||
"Either input text or at least one attachment is required",
|
||||
);
|
||||
}
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.sendTurn",
|
||||
allowRecovery: true,
|
||||
});
|
||||
const turn = yield* routed.adapter.sendTurn(input);
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
provider: routed.adapter.provider,
|
||||
status: "running",
|
||||
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
|
||||
runtimePayload: {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
activeTurnId: turn.turnId,
|
||||
lastRuntimeEvent: "provider.sendTurn",
|
||||
lastRuntimeEventAt: new Date().toISOString(),
|
||||
},
|
||||
});
|
||||
yield* analytics.record("provider.turn.sent", {
|
||||
provider: routed.adapter.provider,
|
||||
model: input.modelSelection?.model,
|
||||
interactionMode: input.interactionMode,
|
||||
attachmentCount: input.attachments.length,
|
||||
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
|
||||
});
|
||||
return turn;
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderServiceShape["interruptTurn"] = Effect.fn("interruptTurn")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.interruptTurn",
|
||||
schema: ProviderInterruptTurnInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.interruptTurn",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.interruptTurn(routed.threadId, input.turnId);
|
||||
yield* analytics.record("provider.turn.interrupted", {
|
||||
provider: routed.adapter.provider,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const respondToRequest: ProviderServiceShape["respondToRequest"] = Effect.fn("respondToRequest")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.respondToRequest",
|
||||
schema: ProviderRespondToRequestInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.respondToRequest",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.respondToRequest(routed.threadId, input.requestId, input.decision);
|
||||
yield* analytics.record("provider.request.responded", {
|
||||
provider: routed.adapter.provider,
|
||||
decision: input.decision,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const respondToUserInput: ProviderServiceShape["respondToUserInput"] = Effect.fn(
|
||||
"respondToUserInput",
|
||||
)(function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.respondToUserInput",
|
||||
schema: ProviderRespondToUserInputInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.respondToUserInput",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.respondToUserInput(routed.threadId, input.requestId, input.answers);
|
||||
});
|
||||
|
||||
const stopSession: ProviderServiceShape["stopSession"] = Effect.fn("stopSession")(
|
||||
function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.stopSession",
|
||||
schema: ProviderStopSessionInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.stopSession",
|
||||
allowRecovery: false,
|
||||
});
|
||||
if (routed.isActive) {
|
||||
yield* routed.adapter.stopSession(routed.threadId);
|
||||
}
|
||||
yield* directory.remove(input.threadId);
|
||||
yield* analytics.record("provider.session.stopped", {
|
||||
provider: routed.adapter.provider,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const listSessions: ProviderServiceShape["listSessions"] = Effect.fn("listSessions")(
|
||||
function* () {
|
||||
const sessionsByProvider = yield* Effect.forEach(adapters, (adapter) =>
|
||||
adapter.listSessions(),
|
||||
);
|
||||
const activeSessions = sessionsByProvider.flatMap((sessions) => sessions);
|
||||
const persistedBindings = yield* directory.listThreadIds().pipe(
|
||||
Effect.flatMap((threadIds) =>
|
||||
Effect.forEach(
|
||||
threadIds,
|
||||
(threadId) =>
|
||||
directory
|
||||
.getBinding(threadId)
|
||||
.pipe(Effect.orElseSucceed(() => Option.none<ProviderRuntimeBinding>())),
|
||||
{ concurrency: "unbounded" },
|
||||
),
|
||||
),
|
||||
Effect.orElseSucceed(() => [] as Array<Option.Option<ProviderRuntimeBinding>>),
|
||||
);
|
||||
const bindingsByThreadId = new Map<ThreadId, ProviderRuntimeBinding>();
|
||||
for (const bindingOption of persistedBindings) {
|
||||
const binding = Option.getOrUndefined(bindingOption);
|
||||
if (binding) {
|
||||
bindingsByThreadId.set(binding.threadId, binding);
|
||||
}
|
||||
}
|
||||
|
||||
return activeSessions.map((session) => {
|
||||
const binding = bindingsByThreadId.get(session.threadId);
|
||||
if (!binding) {
|
||||
return session;
|
||||
}
|
||||
|
||||
const overrides: {
|
||||
resumeCursor?: ProviderSession["resumeCursor"];
|
||||
runtimeMode?: ProviderSession["runtimeMode"];
|
||||
} = {};
|
||||
if (session.resumeCursor === undefined && binding.resumeCursor !== undefined) {
|
||||
overrides.resumeCursor = binding.resumeCursor;
|
||||
}
|
||||
if (binding.runtimeMode !== undefined) {
|
||||
overrides.runtimeMode = binding.runtimeMode;
|
||||
}
|
||||
return Object.assign({}, session, overrides);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const getCapabilities: ProviderServiceShape["getCapabilities"] = (provider) =>
|
||||
registry.getByProvider(provider).pipe(Effect.map((adapter) => adapter.capabilities));
|
||||
|
||||
const rollbackConversation: ProviderServiceShape["rollbackConversation"] = Effect.fn(
|
||||
"rollbackConversation",
|
||||
)(function* (rawInput) {
|
||||
const input = yield* decodeInputOrValidationError({
|
||||
operation: "ProviderService.rollbackConversation",
|
||||
schema: ProviderRollbackConversationInput,
|
||||
payload: rawInput,
|
||||
});
|
||||
if (input.numTurns === 0) {
|
||||
return;
|
||||
}
|
||||
const routed = yield* resolveRoutableSession({
|
||||
threadId: input.threadId,
|
||||
operation: "ProviderService.rollbackConversation",
|
||||
allowRecovery: true,
|
||||
});
|
||||
yield* routed.adapter.rollbackThread(routed.threadId, input.numTurns);
|
||||
yield* analytics.record("provider.conversation.rolled_back", {
|
||||
provider: routed.adapter.provider,
|
||||
turns: input.numTurns,
|
||||
});
|
||||
});
|
||||
|
||||
const runStopAll = Effect.fn("runStopAll")(function* () {
|
||||
const threadIds = yield* directory.listThreadIds();
|
||||
const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
|
||||
adapter.listSessions(),
|
||||
).pipe(Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)));
|
||||
yield* Effect.forEach(activeSessions, (session) =>
|
||||
upsertSessionBinding(session, session.threadId, {
|
||||
lastRuntimeEvent: "provider.stopAll",
|
||||
lastRuntimeEventAt: new Date().toISOString(),
|
||||
}),
|
||||
).pipe(Effect.asVoid);
|
||||
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
|
||||
yield* Effect.forEach(threadIds, (threadId) =>
|
||||
directory.getProvider(threadId).pipe(
|
||||
Effect.flatMap((provider) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
provider,
|
||||
status: "stopped",
|
||||
runtimePayload: {
|
||||
activeTurnId: null,
|
||||
lastRuntimeEvent: "provider.stopAll",
|
||||
lastRuntimeEventAt: new Date().toISOString(),
|
||||
},
|
||||
}),
|
||||
),
|
||||
),
|
||||
).pipe(Effect.asVoid);
|
||||
yield* analytics.record("provider.sessions.stopped_all", {
|
||||
sessionCount: threadIds.length,
|
||||
});
|
||||
yield* analytics.flush;
|
||||
});
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.catch(runStopAll(), (cause) =>
|
||||
Effect.logWarning("failed to stop provider service", { cause }),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
getCapabilities,
|
||||
rollbackConversation,
|
||||
// Each access creates a fresh PubSub subscription so that multiple
|
||||
// consumers (ProviderRuntimeIngestion, CheckpointReactor, etc.) each
|
||||
// independently receive all runtime events.
|
||||
get streamEvents(): ProviderServiceShape["streamEvents"] {
|
||||
return Stream.fromPubSub(runtimeEventPubSub);
|
||||
},
|
||||
} satisfies ProviderServiceShape;
|
||||
});
|
||||
|
||||
export const ProviderServiceLive = Layer.effect(ProviderService, makeProviderService());
|
||||
|
||||
export function makeProviderServiceLive(options?: ProviderServiceLiveOptions) {
|
||||
|
||||
@@ -5,68 +5,70 @@ import * as Semaphore from "effect/Semaphore";
|
||||
import type { ServerProviderShape } from "./Services/ServerProvider";
|
||||
import { ServerSettingsError } from "@t3tools/contracts";
|
||||
|
||||
export function makeManagedServerProvider<Settings>(input: {
|
||||
export const makeManagedServerProvider = Effect.fn("makeManagedServerProvider")(function* <
|
||||
Settings,
|
||||
>(input: {
|
||||
readonly getSettings: Effect.Effect<Settings>;
|
||||
readonly streamSettings: Stream.Stream<Settings>;
|
||||
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
|
||||
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
|
||||
readonly refreshInterval?: Duration.Input;
|
||||
}): Effect.Effect<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
return Effect.gen(function* () {
|
||||
const refreshSemaphore = yield* Semaphore.make(1);
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ServerProvider>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const initialSettings = yield* input.getSettings;
|
||||
const initialSnapshot = yield* input.checkProvider;
|
||||
const snapshotRef = yield* Ref.make(initialSnapshot);
|
||||
const settingsRef = yield* Ref.make(initialSettings);
|
||||
}): Effect.fn.Return<ServerProviderShape, ServerSettingsError, Scope.Scope> {
|
||||
const refreshSemaphore = yield* Semaphore.make(1);
|
||||
const changesPubSub = yield* Effect.acquireRelease(
|
||||
PubSub.unbounded<ServerProvider>(),
|
||||
PubSub.shutdown,
|
||||
);
|
||||
const initialSettings = yield* input.getSettings;
|
||||
const initialSnapshot = yield* input.checkProvider;
|
||||
const snapshotRef = yield* Ref.make(initialSnapshot);
|
||||
const settingsRef = yield* Ref.make(initialSettings);
|
||||
|
||||
const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
|
||||
refreshSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const forceRefresh = options?.forceRefresh === true;
|
||||
const previousSettings = yield* Ref.get(settingsRef);
|
||||
if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
|
||||
yield* Ref.set(settingsRef, nextSettings);
|
||||
return yield* Ref.get(snapshotRef);
|
||||
}
|
||||
const applySnapshotBase = Effect.fn("applySnapshot")(function* (
|
||||
nextSettings: Settings,
|
||||
options?: { readonly forceRefresh?: boolean },
|
||||
) {
|
||||
const forceRefresh = options?.forceRefresh === true;
|
||||
const previousSettings = yield* Ref.get(settingsRef);
|
||||
if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
|
||||
yield* Ref.set(settingsRef, nextSettings);
|
||||
return yield* Ref.get(snapshotRef);
|
||||
}
|
||||
|
||||
const nextSnapshot = yield* input.checkProvider;
|
||||
yield* Ref.set(settingsRef, nextSettings);
|
||||
yield* Ref.set(snapshotRef, nextSnapshot);
|
||||
yield* PubSub.publish(changesPubSub, nextSnapshot);
|
||||
return nextSnapshot;
|
||||
}),
|
||||
);
|
||||
|
||||
const refreshSnapshot = Effect.gen(function* () {
|
||||
const nextSettings = yield* input.getSettings;
|
||||
return yield* applySnapshot(nextSettings, { forceRefresh: true });
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
|
||||
Effect.asVoid(applySnapshot(nextSettings)),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.forever(
|
||||
Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
|
||||
Effect.flatMap(() => refreshSnapshot),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
return {
|
||||
getSnapshot: input.getSettings.pipe(
|
||||
Effect.flatMap(applySnapshot),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orDie,
|
||||
),
|
||||
refresh: refreshSnapshot.pipe(Effect.tapError(Effect.logError), Effect.orDie),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
} satisfies ServerProviderShape;
|
||||
const nextSnapshot = yield* input.checkProvider;
|
||||
yield* Ref.set(settingsRef, nextSettings);
|
||||
yield* Ref.set(snapshotRef, nextSnapshot);
|
||||
yield* PubSub.publish(changesPubSub, nextSnapshot);
|
||||
return nextSnapshot;
|
||||
});
|
||||
}
|
||||
const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
|
||||
refreshSemaphore.withPermits(1)(applySnapshotBase(nextSettings, options));
|
||||
|
||||
const refreshSnapshot = Effect.fn("refreshSnapshot")(function* () {
|
||||
const nextSettings = yield* input.getSettings;
|
||||
return yield* applySnapshot(nextSettings, { forceRefresh: true });
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
|
||||
Effect.asVoid(applySnapshot(nextSettings)),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
yield* Effect.forever(
|
||||
Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
|
||||
Effect.flatMap(() => refreshSnapshot()),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
),
|
||||
).pipe(Effect.forkScoped);
|
||||
|
||||
return {
|
||||
getSnapshot: input.getSettings.pipe(
|
||||
Effect.flatMap(applySnapshot),
|
||||
Effect.tapError(Effect.logError),
|
||||
Effect.orDie,
|
||||
),
|
||||
refresh: refreshSnapshot().pipe(Effect.tapError(Effect.logError), Effect.orDie),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
},
|
||||
} satisfies ServerProviderShape;
|
||||
});
|
||||
@@ -42,6 +42,9 @@ import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResol
|
||||
import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries";
|
||||
import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
|
||||
import { isPerfProviderEnabled } from "./perf/config";
|
||||
import { PerfProviderRegistryLive } from "./perf/PerfProviderRegistry";
|
||||
import { PerfProviderLayerLive } from "./perf/PerfProviderLayers";
|
||||
|
||||
const PtyAdapterLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
@@ -112,7 +115,7 @@ const CheckpointingLayerLive = Layer.empty.pipe(
|
||||
Layer.provideMerge(CheckpointStoreLive),
|
||||
);
|
||||
|
||||
const ProviderLayerLive = Layer.unwrap(
|
||||
const DefaultProviderLayerLive = Layer.unwrap(
|
||||
Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
|
||||
@@ -141,6 +144,14 @@ const ProviderLayerLive = Layer.unwrap(
|
||||
}),
|
||||
);
|
||||
|
||||
const SelectedProviderLayerLive = isPerfProviderEnabled()
|
||||
? PerfProviderLayerLive
|
||||
: DefaultProviderLayerLive;
|
||||
|
||||
const SelectedProviderRegistryLayerLive = isPerfProviderEnabled()
|
||||
? PerfProviderRegistryLive
|
||||
: ProviderRegistryLive;
|
||||
|
||||
const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
|
||||
|
||||
const GitLayerLive = Layer.empty.pipe(
|
||||
@@ -172,12 +183,12 @@ const RuntimeServicesLive = Layer.empty.pipe(
|
||||
// Core Services
|
||||
Layer.provideMerge(CheckpointingLayerLive),
|
||||
Layer.provideMerge(OrchestrationLayerLive),
|
||||
Layer.provideMerge(ProviderLayerLive),
|
||||
Layer.provideMerge(SelectedProviderLayerLive),
|
||||
Layer.provideMerge(GitLayerLive),
|
||||
Layer.provideMerge(TerminalLayerLive),
|
||||
Layer.provideMerge(PersistenceLayerLive),
|
||||
Layer.provideMerge(KeybindingsLive),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SelectedProviderRegistryLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(WorkspaceLayerLive),
|
||||
Layer.provideMerge(ProjectFaviconResolverLive),
|
||||
|
||||
@@ -70,34 +70,35 @@ const makeAnalyticsService = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const sendBatch = (events: ReadonlyArray<BufferedAnalyticsEvent>) =>
|
||||
Effect.gen(function* () {
|
||||
if (!telemetryConfig.enabled || !identifier) return;
|
||||
const sendBatch = Effect.fn("sendBatch")(function* (
|
||||
events: ReadonlyArray<BufferedAnalyticsEvent>,
|
||||
) {
|
||||
if (!telemetryConfig.enabled || !identifier) return;
|
||||
|
||||
const payload = {
|
||||
api_key: telemetryConfig.posthogKey,
|
||||
batch: events.map((event) => ({
|
||||
event: event.event,
|
||||
distinct_id: identifier,
|
||||
properties: {
|
||||
...event.properties,
|
||||
$process_person_profile: false,
|
||||
platform: process.platform,
|
||||
wsl: process.env.WSL_DISTRO_NAME,
|
||||
arch: process.arch,
|
||||
t3CodeVersion: version,
|
||||
clientType,
|
||||
},
|
||||
timestamp: event.capturedAt,
|
||||
})),
|
||||
};
|
||||
const payload = {
|
||||
api_key: telemetryConfig.posthogKey,
|
||||
batch: events.map((event) => ({
|
||||
event: event.event,
|
||||
distinct_id: identifier,
|
||||
properties: {
|
||||
...event.properties,
|
||||
$process_person_profile: false,
|
||||
platform: process.platform,
|
||||
wsl: process.env.WSL_DISTRO_NAME,
|
||||
arch: process.arch,
|
||||
t3CodeVersion: version,
|
||||
clientType,
|
||||
},
|
||||
timestamp: event.capturedAt,
|
||||
})),
|
||||
};
|
||||
|
||||
yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
|
||||
HttpClientRequest.bodyJson(payload),
|
||||
Effect.flatMap(httpClient.execute),
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
);
|
||||
});
|
||||
yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
|
||||
HttpClientRequest.bodyJson(payload),
|
||||
Effect.flatMap(httpClient.execute),
|
||||
Effect.flatMap(HttpClientResponse.filterStatusOk),
|
||||
);
|
||||
});
|
||||
|
||||
const flush: AnalyticsServiceShape["flush"] = Effect.gen(function* () {
|
||||
while (true) {
|
||||
|
||||
@@ -11,7 +11,9 @@
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"test:browser": "vitest run --config vitest.browser.config.ts",
|
||||
"test:browser:install": "playwright install --with-deps chromium"
|
||||
"test:browser:install": "playwright install --with-deps chromium",
|
||||
"test:perf": "vitest run --config vitest.perf.config.ts",
|
||||
"test:perf:install": "playwright install --with-deps chromium"
|
||||
},
|
||||
"dependencies": {
|
||||
"@base-ui/react": "^1.2.0",
|
||||
|
||||
@@ -1407,6 +1407,52 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("opens the project cwd with Trae when it is the only available editor", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
availableEditors: ["trae"],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await waitForServerConfigToApply();
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "Open",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
await vi.waitFor(() => {
|
||||
expect(openButton.disabled).toBe(false);
|
||||
});
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.shellOpenInEditor,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.shellOpenInEditor,
|
||||
cwd: "/repo/project",
|
||||
editor: "trae",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("filters the open picker menu and opens VSCodium from the menu", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
|
||||
@@ -3750,7 +3750,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
|
||||
<div
|
||||
className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background"
|
||||
data-testid={`chat-thread-${activeThread.id}`}
|
||||
>
|
||||
{/* Top bar */}
|
||||
<header
|
||||
className={cn(
|
||||
|
||||
@@ -20,6 +20,20 @@ export const CursorIcon: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const TraeIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 24 24" fill="currentColor">
|
||||
{/* Back rectangle: left strip + bottom strip drawn separately — empty bottom-left corner is the gap between them */}
|
||||
<rect x="1" y="4" width="3" height="14" />
|
||||
<rect x="4" y="18" width="18" height="3" />
|
||||
{/* Front frame: top bar + right bar only — left and bottom are replaced by the back strips above */}
|
||||
<rect x="4" y="4" width="18" height="3" />
|
||||
<rect x="19" y="7" width="3" height="11" />
|
||||
{/* Two diamonds, offset slightly to the right within the open area */}
|
||||
<path d="M11 10L13 12L11 14L9 12Z" />
|
||||
<path d="M16 10L18 12L16 14L14 12Z" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const VisualStudioCode: Icon = (props) => {
|
||||
const id = useId();
|
||||
const maskId = `${id}-vscode-a`;
|
||||
|
||||
@@ -6,7 +6,7 @@ import { ChevronDownIcon, FolderClosedIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { Group, GroupSeparator } from "../ui/group";
|
||||
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "../ui/menu";
|
||||
import { AntigravityIcon, CursorIcon, Icon, VisualStudioCode, Zed } from "../Icons";
|
||||
import { AntigravityIcon, CursorIcon, Icon, TraeIcon, VisualStudioCode, Zed } from "../Icons";
|
||||
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
|
||||
@@ -17,6 +17,11 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
|
||||
Icon: CursorIcon,
|
||||
value: "cursor",
|
||||
},
|
||||
{
|
||||
label: "Trae",
|
||||
Icon: TraeIcon,
|
||||
value: "trae",
|
||||
},
|
||||
{
|
||||
label: "VS Code",
|
||||
Icon: VisualStudioCode,
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { access, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { createServer } from "node:net";
|
||||
import { join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { once } from "node:events";
|
||||
|
||||
import { chromium, type Browser, type BrowserContext, type Page } from "playwright";
|
||||
|
||||
import {
|
||||
type BrowserPerfMetrics,
|
||||
summarizeBrowserPerfMetrics,
|
||||
type PerfRunArtifact,
|
||||
type PerfServerMetricSample,
|
||||
writePerfArtifact,
|
||||
} from "../../../../test/perf/support/artifact";
|
||||
import {
|
||||
installBrowserPerfCollector,
|
||||
PERF_BROWSER_GLOBAL,
|
||||
} from "../../../../test/perf/support/browserMetrics";
|
||||
import type { PerfThresholdProfile } from "../../../../test/perf/support/thresholds";
|
||||
import type {
|
||||
PerfProviderScenarioId,
|
||||
PerfSeedScenarioId,
|
||||
} from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import {
|
||||
NoopServerSampler,
|
||||
type PerfServerSampler,
|
||||
} from "../../../../test/perf/support/serverSampler";
|
||||
import { buildPerfServerEnv } from "./serverEnv";
|
||||
|
||||
const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url));
|
||||
const serverBinPath = resolve(repoRoot, "apps/server/dist/bin.mjs");
|
||||
const serverClientIndexPath = resolve(repoRoot, "apps/server/dist/client/index.html");
|
||||
const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
|
||||
const PERF_HEADFUL_ENV = "T3CODE_PERF_HEADFUL";
|
||||
const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__";
|
||||
const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__";
|
||||
|
||||
interface PerfSeedThreadSummary {
|
||||
readonly id: string;
|
||||
readonly projectId: string;
|
||||
readonly projectTitle: string | null;
|
||||
readonly title: string;
|
||||
readonly turnCount: number | null;
|
||||
readonly messageCount: number;
|
||||
readonly activityCount: number;
|
||||
readonly proposedPlanCount: number;
|
||||
readonly checkpointCount: number;
|
||||
}
|
||||
|
||||
interface PerfSeedProjectSummary {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly workspaceRoot: string;
|
||||
readonly threadCount: number;
|
||||
}
|
||||
|
||||
export interface PerfSeededState {
|
||||
readonly scenarioId: PerfSeedScenarioId;
|
||||
readonly runParentDir: string;
|
||||
readonly baseDir: string;
|
||||
readonly workspaceRoot: string;
|
||||
readonly projectTitle: string | null;
|
||||
readonly projectSummaries: ReadonlyArray<PerfSeedProjectSummary>;
|
||||
readonly threadSummaries: ReadonlyArray<PerfSeedThreadSummary>;
|
||||
}
|
||||
|
||||
interface StartPerfAppHarnessOptions {
|
||||
readonly suite: string;
|
||||
readonly seedScenarioId: PerfSeedScenarioId;
|
||||
readonly providerScenarioId?: PerfProviderScenarioId;
|
||||
readonly serverSampler?: PerfServerSampler;
|
||||
}
|
||||
|
||||
interface FinishPerfRunOptions {
|
||||
readonly suite: string;
|
||||
readonly scenarioId: string;
|
||||
readonly thresholds: PerfThresholdProfile;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
readonly actionSummary?: {
|
||||
readonly threadSwitchActionPrefix?: string;
|
||||
readonly burstActionName?: string;
|
||||
};
|
||||
readonly artifactBasename?: string;
|
||||
}
|
||||
|
||||
export interface PerfAppHarness {
|
||||
readonly seededState: PerfSeededState;
|
||||
readonly page: Page;
|
||||
readonly url: string;
|
||||
readonly artifactDir: string;
|
||||
readonly startAction: (name: string) => Promise<void>;
|
||||
readonly endAction: (name: string) => Promise<number | null>;
|
||||
readonly resetBrowserMetrics: () => Promise<void>;
|
||||
readonly sampleMountedRows: (label: string) => Promise<number>;
|
||||
readonly snapshotBrowserMetrics: () => Promise<BrowserPerfMetrics>;
|
||||
readonly finishRun: (options: FinishPerfRunOptions) => Promise<{
|
||||
readonly artifactPath: string;
|
||||
readonly artifact: PerfRunArtifact;
|
||||
readonly browserMetrics: BrowserPerfMetrics;
|
||||
readonly serverMetrics: ReadonlyArray<PerfServerMetricSample> | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
async function pickFreePort(): Promise<number> {
|
||||
return await new Promise<number>((resolvePort, reject) => {
|
||||
const server = createServer();
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Unable to resolve a free localhost port."));
|
||||
return;
|
||||
}
|
||||
const { port } = address;
|
||||
server.close((closeError) => {
|
||||
if (closeError) {
|
||||
reject(closeError);
|
||||
return;
|
||||
}
|
||||
resolvePort(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function waitForServerReady(url: string, process: ChildProcess): Promise<void> {
|
||||
const startedAt = Date.now();
|
||||
const timeoutMs = 45_000;
|
||||
const requestTimeoutMs = 1_000;
|
||||
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
if (process.exitCode !== null) {
|
||||
throw new Error(`Perf server exited early with code ${process.exitCode}.`);
|
||||
}
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
redirect: "manual",
|
||||
signal: AbortSignal.timeout(requestTimeoutMs),
|
||||
});
|
||||
if (response.ok) {
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Ignore connection races while the server is still starting.
|
||||
}
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 200));
|
||||
}
|
||||
|
||||
throw new Error(`Timed out waiting for perf server readiness at ${url}.`);
|
||||
}
|
||||
|
||||
async function verifyBuiltArtifacts(): Promise<void> {
|
||||
await Promise.all([access(serverBinPath), access(serverClientIndexPath)]).catch(() => {
|
||||
throw new Error(
|
||||
`Built perf artifacts are missing. Expected ${serverBinPath} and ${serverClientIndexPath}. Run bun run test:perf:web or build the app first.`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function stopChildProcess(process: ChildProcess): Promise<void> {
|
||||
if (process.exitCode !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.kill("SIGTERM");
|
||||
const exited = await new Promise<boolean>((resolveExited) => {
|
||||
const timer = setTimeout(() => resolveExited(false), 5_000);
|
||||
process.once("exit", () => {
|
||||
clearTimeout(timer);
|
||||
resolveExited(true);
|
||||
});
|
||||
});
|
||||
|
||||
if (!exited && process.exitCode === null) {
|
||||
process.kill("SIGKILL");
|
||||
await new Promise<void>((resolveExited) => {
|
||||
process.once("exit", () => resolveExited());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureArtifactDir(suite: string, scenarioId: string): Promise<string> {
|
||||
const baseArtifactDir = resolve(
|
||||
process.env[PERF_ARTIFACT_DIR_ENV] ?? join(repoRoot, "artifacts/perf"),
|
||||
);
|
||||
const runId = `${suite}-${scenarioId}-${Date.now().toString()}`;
|
||||
const artifactDir = join(baseArtifactDir, runId);
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
return artifactDir;
|
||||
}
|
||||
|
||||
async function cleanupPerfRunDir(runParentDir: string): Promise<void> {
|
||||
await rm(runParentDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
async function writeServerLogs(
|
||||
artifactDir: string,
|
||||
stdout: string,
|
||||
stderr: string,
|
||||
basename: string,
|
||||
): Promise<void> {
|
||||
await mkdir(artifactDir, { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(join(artifactDir, `${basename}.server.stdout.log`), stdout, "utf8"),
|
||||
writeFile(join(artifactDir, `${basename}.server.stderr.log`), stderr, "utf8"),
|
||||
]);
|
||||
}
|
||||
|
||||
async function invokeBrowserCollector<T>(
|
||||
page: Page,
|
||||
fn: (collectorName: string, ...args: ReadonlyArray<unknown>) => T,
|
||||
...args: ReadonlyArray<unknown>
|
||||
): Promise<T> {
|
||||
return await page.evaluate(
|
||||
({ collectorName, args: serializedArgs, fnSource }) => {
|
||||
const runtimeFn = new Function(
|
||||
"collectorName",
|
||||
"args",
|
||||
`return (${fnSource})(collectorName, ...args);`,
|
||||
) as (collectorName: string, args: ReadonlyArray<unknown>) => T;
|
||||
return runtimeFn(collectorName, serializedArgs);
|
||||
},
|
||||
{
|
||||
collectorName: PERF_BROWSER_GLOBAL,
|
||||
args,
|
||||
fnSource: fn.toString(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function parsePerfSeededState(stdout: string): PerfSeededState {
|
||||
const startIndex = stdout.lastIndexOf(PERF_SEED_JSON_START);
|
||||
const endIndex = stdout.lastIndexOf(PERF_SEED_JSON_END);
|
||||
|
||||
if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {
|
||||
const payload = stdout.slice(startIndex + PERF_SEED_JSON_START.length, endIndex).trim();
|
||||
return JSON.parse(payload) as PerfSeededState;
|
||||
}
|
||||
|
||||
return JSON.parse(stdout) as PerfSeededState;
|
||||
}
|
||||
|
||||
export async function startPerfAppHarness(
|
||||
options: StartPerfAppHarnessOptions,
|
||||
): Promise<PerfAppHarness> {
|
||||
await verifyBuiltArtifacts();
|
||||
|
||||
const seededState = await (async () => {
|
||||
const seedProcess = spawn(
|
||||
"bun",
|
||||
["run", "apps/server/scripts/seedPerfState.ts", options.seedScenarioId],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env: process.env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
seedProcess.stdout?.on("data", (chunk) => {
|
||||
stdout += chunk.toString();
|
||||
});
|
||||
seedProcess.stderr?.on("data", (chunk) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
const [exitCode] = (await once(seedProcess, "exit")) as [number | null];
|
||||
if (exitCode !== 0) {
|
||||
throw new Error(`Perf seed command failed with code ${exitCode ?? "unknown"}.\n${stderr}`);
|
||||
}
|
||||
return parsePerfSeededState(stdout);
|
||||
})();
|
||||
const artifactDir = await ensureArtifactDir(options.suite, options.seedScenarioId);
|
||||
const port = await pickFreePort();
|
||||
const url = `http://127.0.0.1:${port}/`;
|
||||
const env = buildPerfServerEnv(process.env, options.providerScenarioId);
|
||||
|
||||
let stdoutBuffer = "";
|
||||
let stderrBuffer = "";
|
||||
const serverProcess = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
serverBinPath,
|
||||
"--mode",
|
||||
"web",
|
||||
"--host",
|
||||
"127.0.0.1",
|
||||
"--port",
|
||||
`${port}`,
|
||||
"--base-dir",
|
||||
seededState.baseDir,
|
||||
"--no-browser",
|
||||
],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
},
|
||||
);
|
||||
serverProcess.stdout?.on("data", (chunk) => {
|
||||
stdoutBuffer += chunk.toString();
|
||||
});
|
||||
serverProcess.stderr?.on("data", (chunk) => {
|
||||
stderrBuffer += chunk.toString();
|
||||
});
|
||||
let browser: Browser | null = null;
|
||||
let context: BrowserContext | null = null;
|
||||
let page: Page | null = null;
|
||||
|
||||
try {
|
||||
await waitForServerReady(url, serverProcess);
|
||||
|
||||
browser = await chromium.launch({
|
||||
headless: process.env[PERF_HEADFUL_ENV] !== "1",
|
||||
});
|
||||
context = await browser.newContext({
|
||||
viewport: { width: 1440, height: 960 },
|
||||
});
|
||||
await context.addInitScript(installBrowserPerfCollector, "[data-timeline-row-kind]");
|
||||
page = await context.newPage();
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
|
||||
const firstProjectTitle =
|
||||
seededState.projectSummaries[0]?.title ??
|
||||
seededState.projectTitle ??
|
||||
getPerfSeedScenario(options.seedScenarioId).projects[0]?.title;
|
||||
if (!firstProjectTitle) {
|
||||
throw new Error(`Seed scenario '${options.seedScenarioId}' produced no projects.`);
|
||||
}
|
||||
await page.getByText(firstProjectTitle, { exact: true }).first().waitFor({ timeout: 45_000 });
|
||||
|
||||
const sampler = options.serverSampler ?? new NoopServerSampler();
|
||||
if (serverProcess.pid) {
|
||||
await sampler.start({ pid: serverProcess.pid });
|
||||
}
|
||||
const runStartedAt = new Date().toISOString();
|
||||
const readyPage = page;
|
||||
if (!readyPage) {
|
||||
throw new Error("Perf app harness did not initialize a browser page.");
|
||||
}
|
||||
|
||||
let finishPromise:
|
||||
| Promise<{
|
||||
readonly artifactPath: string;
|
||||
readonly artifact: PerfRunArtifact;
|
||||
readonly browserMetrics: BrowserPerfMetrics;
|
||||
readonly serverMetrics: ReadonlyArray<PerfServerMetricSample> | null;
|
||||
}>
|
||||
| undefined;
|
||||
|
||||
const teardown = async () => {
|
||||
await Promise.allSettled([
|
||||
context ? context.close() : Promise.resolve(),
|
||||
browser ? browser.close() : Promise.resolve(),
|
||||
]);
|
||||
await stopChildProcess(serverProcess);
|
||||
await cleanupPerfRunDir(seededState.runParentDir);
|
||||
};
|
||||
|
||||
return {
|
||||
seededState,
|
||||
page: readyPage,
|
||||
url,
|
||||
artifactDir,
|
||||
startAction: (name) =>
|
||||
invokeBrowserCollector(
|
||||
readyPage,
|
||||
(collectorName, actionName) => {
|
||||
(window as Window & Record<string, any>)[collectorName]?.startAction(
|
||||
actionName as string,
|
||||
);
|
||||
},
|
||||
name,
|
||||
),
|
||||
endAction: (name) =>
|
||||
invokeBrowserCollector(
|
||||
readyPage,
|
||||
(collectorName, actionName) => {
|
||||
return (
|
||||
(window as Window & Record<string, any>)[collectorName]?.endAction(
|
||||
actionName as string,
|
||||
) ?? null
|
||||
);
|
||||
},
|
||||
name,
|
||||
),
|
||||
resetBrowserMetrics: () =>
|
||||
invokeBrowserCollector(readyPage, (collectorName) => {
|
||||
(window as Window & Record<string, any>)[collectorName]?.reset();
|
||||
}),
|
||||
sampleMountedRows: (label) =>
|
||||
invokeBrowserCollector(
|
||||
readyPage,
|
||||
(collectorName, sampleLabel) => {
|
||||
return (
|
||||
(window as Window & Record<string, any>)[collectorName]?.sampleMountedRows(
|
||||
sampleLabel as string,
|
||||
) ?? 0
|
||||
);
|
||||
},
|
||||
label,
|
||||
),
|
||||
snapshotBrowserMetrics: () =>
|
||||
invokeBrowserCollector(readyPage, (collectorName) => {
|
||||
return ((window as Window & Record<string, any>)[collectorName]?.snapshot() ?? {
|
||||
actions: [],
|
||||
longTasks: [],
|
||||
rafGapsMs: [],
|
||||
mountedRowSamples: [],
|
||||
}) as BrowserPerfMetrics;
|
||||
}),
|
||||
finishRun: async (finishOptions) => {
|
||||
if (finishPromise) {
|
||||
return await finishPromise;
|
||||
}
|
||||
|
||||
finishPromise = (async () => {
|
||||
const completedAt = new Date().toISOString();
|
||||
const browserMetrics: BrowserPerfMetrics = await (async () => {
|
||||
try {
|
||||
return await invokeBrowserCollector(readyPage, (collectorName) => {
|
||||
return ((window as Window & Record<string, any>)[collectorName]?.snapshot() ?? {
|
||||
actions: [],
|
||||
longTasks: [],
|
||||
rafGapsMs: [],
|
||||
mountedRowSamples: [],
|
||||
}) as BrowserPerfMetrics;
|
||||
});
|
||||
} catch {
|
||||
return {
|
||||
actions: [],
|
||||
longTasks: [],
|
||||
rafGapsMs: [],
|
||||
mountedRowSamples: [],
|
||||
} satisfies BrowserPerfMetrics;
|
||||
}
|
||||
})();
|
||||
const serverMetrics = await sampler.stop();
|
||||
await teardown();
|
||||
|
||||
const basename =
|
||||
finishOptions.artifactBasename ?? `${finishOptions.suite}-${finishOptions.scenarioId}`;
|
||||
await writeServerLogs(artifactDir, stdoutBuffer, stderrBuffer, basename);
|
||||
const artifact: PerfRunArtifact = {
|
||||
suite: finishOptions.suite,
|
||||
scenarioId: finishOptions.scenarioId,
|
||||
startedAt: runStartedAt,
|
||||
completedAt,
|
||||
thresholds: finishOptions.thresholds,
|
||||
summary: summarizeBrowserPerfMetrics(browserMetrics, finishOptions.actionSummary),
|
||||
browserMetrics,
|
||||
serverMetrics,
|
||||
...(finishOptions.metadata ? { metadata: finishOptions.metadata } : {}),
|
||||
};
|
||||
const artifactPath = join(artifactDir, `${basename}.json`);
|
||||
await writePerfArtifact(artifactPath, artifact);
|
||||
|
||||
return {
|
||||
artifactPath,
|
||||
artifact,
|
||||
browserMetrics,
|
||||
serverMetrics,
|
||||
};
|
||||
})();
|
||||
|
||||
return await finishPromise;
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await Promise.allSettled([
|
||||
context ? context.close() : Promise.resolve(),
|
||||
browser ? browser.close() : Promise.resolve(),
|
||||
]);
|
||||
await stopChildProcess(serverProcess);
|
||||
await cleanupPerfRunDir(seededState.runParentDir);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import type { Page } from "playwright";
|
||||
|
||||
import type { PerfAppHarness } from "./appHarness";
|
||||
|
||||
export async function ensureThreadRowVisible(
|
||||
page: Page,
|
||||
projectTitle: string,
|
||||
threadId: string,
|
||||
): Promise<void> {
|
||||
const threadRow = page.getByTestId(`thread-row-${threadId}`);
|
||||
if (await threadRow.isVisible().catch(() => false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projectToggle = page.getByText(projectTitle, { exact: true }).first();
|
||||
await projectToggle.click();
|
||||
await threadRow.waitFor({ state: "visible", timeout: 20_000 });
|
||||
}
|
||||
|
||||
export async function waitForThreadRoute(
|
||||
page: Page,
|
||||
input: {
|
||||
readonly threadId: string;
|
||||
readonly messageId?: string;
|
||||
readonly extraSelector?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
const path = `/${encodeURIComponent(input.threadId)}`;
|
||||
const threadSelector = `[data-testid="chat-thread-${input.threadId}"]`;
|
||||
await page.waitForFunction(
|
||||
({ expectedPath, threadSelector, messageSelector, extraSelector }) => {
|
||||
const pathMatches = window.location.pathname === expectedPath;
|
||||
if (!pathMatches) {
|
||||
return false;
|
||||
}
|
||||
if (!document.querySelector(threadSelector)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (messageSelector && !document.querySelector(messageSelector)) {
|
||||
return false;
|
||||
}
|
||||
if (extraSelector && !document.querySelector(extraSelector)) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
{
|
||||
expectedPath: path,
|
||||
threadSelector,
|
||||
messageSelector: input.messageId ? `[data-message-id="${input.messageId}"]` : null,
|
||||
extraSelector: input.extraSelector ?? null,
|
||||
},
|
||||
{ timeout: 45_000 },
|
||||
);
|
||||
}
|
||||
|
||||
export async function measureThreadSwitch(
|
||||
harness: PerfAppHarness,
|
||||
input: {
|
||||
readonly actionName: string;
|
||||
readonly projectTitle: string;
|
||||
readonly threadId: string;
|
||||
readonly messageId?: string;
|
||||
readonly extraSelector?: string;
|
||||
},
|
||||
): Promise<number | null> {
|
||||
await ensureThreadRowVisible(harness.page, input.projectTitle, input.threadId);
|
||||
await harness.startAction(input.actionName);
|
||||
await harness.page.getByTestId(`thread-row-${input.threadId}`).click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: input.threadId,
|
||||
...(input.messageId ? { messageId: input.messageId } : {}),
|
||||
...(input.extraSelector ? { extraSelector: input.extraSelector } : {}),
|
||||
});
|
||||
return await harness.endAction(input.actionName);
|
||||
}
|
||||
|
||||
export async function scrollTimelineTo(page: Page, position: "top" | "bottom"): Promise<void> {
|
||||
await page.evaluate(async (targetPosition) => {
|
||||
const timelineRoot = document.querySelector<HTMLElement>('[data-timeline-root="true"]');
|
||||
const scrollContainer = timelineRoot?.parentElement;
|
||||
if (!scrollContainer) {
|
||||
throw new Error("Messages scroll container not found.");
|
||||
}
|
||||
|
||||
scrollContainer.scrollTo({
|
||||
top: targetPosition === "bottom" ? scrollContainer.scrollHeight : 0,
|
||||
behavior: "auto",
|
||||
});
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
|
||||
});
|
||||
}, position);
|
||||
}
|
||||
|
||||
export async function typeIntoComposerAndSend(page: Page, message: string): Promise<void> {
|
||||
const editor = page.getByTestId("composer-editor");
|
||||
await editor.click();
|
||||
await page.keyboard.type(message);
|
||||
await page.getByRole("button", { name: "Send message" }).click();
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { PerfProviderScenarioId } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
|
||||
export const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
|
||||
export const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
const AUTO_BOOTSTRAP_PROJECT_ENV = "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD";
|
||||
|
||||
export function buildPerfServerEnv(
|
||||
baseEnv: NodeJS.ProcessEnv,
|
||||
providerScenarioId?: PerfProviderScenarioId,
|
||||
): NodeJS.ProcessEnv {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
...baseEnv,
|
||||
[AUTO_BOOTSTRAP_PROJECT_ENV]: "false",
|
||||
};
|
||||
|
||||
if (!providerScenarioId) {
|
||||
delete env[PERF_PROVIDER_ENV];
|
||||
delete env[PERF_SCENARIO_ENV];
|
||||
return env;
|
||||
}
|
||||
|
||||
return {
|
||||
...env,
|
||||
[PERF_PROVIDER_ENV]: "1",
|
||||
[PERF_SCENARIO_ENV]: providerScenarioId,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { percentile } from "../../../../test/perf/support/artifact";
|
||||
import { installBrowserPerfCollector } from "../../../../test/perf/support/browserMetrics";
|
||||
import { buildPerfServerEnv, PERF_PROVIDER_ENV, PERF_SCENARIO_ENV } from "./serverEnv";
|
||||
|
||||
describe("percentile", () => {
|
||||
it("returns the minimum value for the zero percentile", () => {
|
||||
expect(percentile([9, 3, 6], 0)).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("installBrowserPerfCollector", () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("cancels the previous animation frame loop before reset starts a new one", () => {
|
||||
let nextHandle = 1;
|
||||
const callbacks = new Map<number, FrameRequestCallback>();
|
||||
const requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {
|
||||
const handle = nextHandle++;
|
||||
callbacks.set(handle, callback);
|
||||
return handle;
|
||||
});
|
||||
const cancelAnimationFrame = vi.fn((handle: number) => {
|
||||
callbacks.delete(handle);
|
||||
});
|
||||
|
||||
vi.stubGlobal("window", {
|
||||
requestAnimationFrame,
|
||||
cancelAnimationFrame,
|
||||
} as unknown as Window & typeof globalThis);
|
||||
vi.stubGlobal("document", {
|
||||
querySelectorAll: vi.fn(() => []),
|
||||
} as unknown as Document);
|
||||
vi.stubGlobal("PerformanceObserver", undefined);
|
||||
|
||||
installBrowserPerfCollector();
|
||||
|
||||
const collector = window.__t3PerfCollector;
|
||||
expect(collector).toBeDefined();
|
||||
expect(requestAnimationFrame).toHaveBeenCalledTimes(1);
|
||||
|
||||
collector?.reset();
|
||||
expect(cancelAnimationFrame).toHaveBeenCalledWith(1);
|
||||
expect(requestAnimationFrame).toHaveBeenCalledTimes(2);
|
||||
|
||||
collector?.reset();
|
||||
expect(cancelAnimationFrame).toHaveBeenLastCalledWith(2);
|
||||
expect(requestAnimationFrame).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPerfServerEnv", () => {
|
||||
it("does not enable the perf provider when no live provider scenario is requested", () => {
|
||||
const env = buildPerfServerEnv({
|
||||
[PERF_PROVIDER_ENV]: "1",
|
||||
[PERF_SCENARIO_ENV]: "dense_assistant_stream",
|
||||
KEEP_ME: "yes",
|
||||
});
|
||||
|
||||
expect(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).toBe("false");
|
||||
expect(env[PERF_PROVIDER_ENV]).toBeUndefined();
|
||||
expect(env[PERF_SCENARIO_ENV]).toBeUndefined();
|
||||
expect(env.KEEP_ME).toBe("yes");
|
||||
});
|
||||
|
||||
it("enables the perf provider only when a live provider scenario is requested", () => {
|
||||
const env = buildPerfServerEnv({}, "dense_assistant_stream");
|
||||
|
||||
expect(env.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).toBe("false");
|
||||
expect(env[PERF_PROVIDER_ENV]).toBe("1");
|
||||
expect(env[PERF_SCENARIO_ENV]).toBe("dense_assistant_stream");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,181 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { summarizeBrowserPerfMetrics } from "../../../../test/perf/support/artifact";
|
||||
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { PERF_THRESHOLDS } from "../../../../test/perf/support/thresholds";
|
||||
import { startPerfAppHarness, type PerfAppHarness } from "./appHarness";
|
||||
import {
|
||||
ensureThreadRowVisible,
|
||||
measureThreadSwitch,
|
||||
scrollTimelineTo,
|
||||
waitForThreadRoute,
|
||||
} from "./pagePerfHelpers";
|
||||
|
||||
test("virtualization stays bounded and heavy thread switches remain snappy", async () => {
|
||||
const thresholds = PERF_THRESHOLDS.local;
|
||||
let harness: PerfAppHarness | null = null;
|
||||
let finished = false;
|
||||
|
||||
try {
|
||||
harness = await startPerfAppHarness({
|
||||
suite: "virtualization",
|
||||
seedScenarioId: "large_threads",
|
||||
});
|
||||
|
||||
const heavyAThreadSummary = harness.seededState.threadSummaries.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
const heavyBThreadSummary = harness.seededState.threadSummaries.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
);
|
||||
const heavyAProjectTitle =
|
||||
heavyAThreadSummary?.projectTitle ?? PERF_CATALOG_IDS.largeThreads.heavyAProjectTitle;
|
||||
const heavyBProjectTitle =
|
||||
heavyBThreadSummary?.projectTitle ?? PERF_CATALOG_IDS.largeThreads.heavyBProjectTitle;
|
||||
const heavyThreadMessageCount = heavyAThreadSummary?.messageCount ?? 0;
|
||||
expect(heavyAThreadSummary).toBeDefined();
|
||||
expect(heavyBThreadSummary).toBeDefined();
|
||||
expect(heavyThreadMessageCount).toBeGreaterThanOrEqual(2_000);
|
||||
expect(heavyAThreadSummary?.turnCount ?? 0).toBeLessThan(100);
|
||||
expect(heavyBThreadSummary?.turnCount ?? 0).toBeLessThan(100);
|
||||
|
||||
await ensureThreadRowVisible(
|
||||
harness.page,
|
||||
heavyAProjectTitle,
|
||||
PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
);
|
||||
await harness.page
|
||||
.getByTestId(`thread-row-${PERF_CATALOG_IDS.largeThreads.heavyAThreadId}`)
|
||||
.click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
});
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
|
||||
await ensureThreadRowVisible(
|
||||
harness.page,
|
||||
heavyBProjectTitle,
|
||||
PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
);
|
||||
await harness.page
|
||||
.getByTestId(`thread-row-${PERF_CATALOG_IDS.largeThreads.heavyBThreadId}`)
|
||||
.click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
});
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
|
||||
await harness.resetBrowserMetrics();
|
||||
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: "thread-switch-warmup-a",
|
||||
projectTitle: heavyAProjectTitle,
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
});
|
||||
|
||||
const mountedRows = await harness.sampleMountedRows("heavy-a-open");
|
||||
expect(mountedRows).toBeLessThanOrEqual(thresholds.maxMountedTimelineRows);
|
||||
|
||||
const measuredTargets = [
|
||||
{
|
||||
actionName: "thread-switch-1",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-2",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-3",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-4",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-5",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyBThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyBTerminalMessageId,
|
||||
},
|
||||
{
|
||||
actionName: "thread-switch-6",
|
||||
threadId: PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
messageId: PERF_CATALOG_IDS.largeThreads.heavyATerminalMessageId,
|
||||
},
|
||||
] as const;
|
||||
|
||||
for (const target of measuredTargets) {
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: target.actionName,
|
||||
projectTitle:
|
||||
target.threadId === PERF_CATALOG_IDS.largeThreads.heavyAThreadId
|
||||
? heavyAProjectTitle
|
||||
: heavyBProjectTitle,
|
||||
threadId: target.threadId,
|
||||
messageId: target.messageId,
|
||||
});
|
||||
await harness.sampleMountedRows(`${target.actionName}-rows`);
|
||||
}
|
||||
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
await harness.sampleMountedRows("scroll-start");
|
||||
await scrollTimelineTo(harness.page, "top");
|
||||
await harness.sampleMountedRows("scroll-top");
|
||||
await scrollTimelineTo(harness.page, "bottom");
|
||||
await harness.sampleMountedRows("scroll-bottom");
|
||||
|
||||
const browserMetrics = await harness.snapshotBrowserMetrics();
|
||||
const summary = summarizeBrowserPerfMetrics(browserMetrics, {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
});
|
||||
|
||||
expect(summary.threadSwitchP50Ms).not.toBeNull();
|
||||
expect(summary.threadSwitchP95Ms).not.toBeNull();
|
||||
expect(summary.threadSwitchP50Ms ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(
|
||||
thresholds.threadSwitchP50Ms,
|
||||
);
|
||||
expect(summary.threadSwitchP95Ms ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(
|
||||
thresholds.threadSwitchP95Ms,
|
||||
);
|
||||
expect(summary.maxMountedTimelineRows).toBeLessThanOrEqual(thresholds.maxMountedTimelineRows);
|
||||
expect(summary.maxLongTaskMs).toBeLessThanOrEqual(thresholds.maxLongTaskMs);
|
||||
expect(summary.maxRafGapMs).toBeLessThanOrEqual(thresholds.maxRafGapMs);
|
||||
|
||||
await harness.finishRun({
|
||||
suite: "virtualization",
|
||||
scenarioId: "large_threads",
|
||||
thresholds,
|
||||
metadata: {
|
||||
heavyThreadMessageCount,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
},
|
||||
});
|
||||
finished = true;
|
||||
} finally {
|
||||
if (harness && !finished) {
|
||||
await harness.finishRun({
|
||||
suite: "virtualization",
|
||||
scenarioId: "large_threads",
|
||||
thresholds,
|
||||
metadata: {
|
||||
heavyThreadMessageCount: harness.seededState.threadSummaries.find(
|
||||
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
|
||||
)?.messageCount,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import { expect, test } from "vitest";
|
||||
|
||||
import { summarizeBrowserPerfMetrics } from "../../../../test/perf/support/artifact";
|
||||
import { PERF_CATALOG_IDS, PERF_PROVIDER_SCENARIOS } from "@t3tools/shared/perf/scenarioCatalog";
|
||||
import { PERF_THRESHOLDS } from "../../../../test/perf/support/thresholds";
|
||||
import { startPerfAppHarness, type PerfAppHarness } from "./appHarness";
|
||||
import {
|
||||
ensureThreadRowVisible,
|
||||
measureThreadSwitch,
|
||||
typeIntoComposerAndSend,
|
||||
waitForThreadRoute,
|
||||
} from "./pagePerfHelpers";
|
||||
|
||||
test("high-frequency websocket events stay responsive under real built-app flow", async () => {
|
||||
const thresholds = PERF_THRESHOLDS.local;
|
||||
let harness: PerfAppHarness | null = null;
|
||||
let finished = false;
|
||||
|
||||
try {
|
||||
harness = await startPerfAppHarness({
|
||||
suite: "websocket-application",
|
||||
seedScenarioId: "burst_base",
|
||||
providerScenarioId: "dense_assistant_stream",
|
||||
});
|
||||
|
||||
const projectTitle = harness.seededState.projectTitle ?? "Performance Workspace";
|
||||
const streamScenario = PERF_PROVIDER_SCENARIOS.dense_assistant_stream;
|
||||
expect(streamScenario.totalDurationMs).toBeGreaterThanOrEqual(10_000);
|
||||
|
||||
await ensureThreadRowVisible(
|
||||
harness.page,
|
||||
projectTitle,
|
||||
PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
);
|
||||
await harness.page
|
||||
.getByTestId(`thread-row-${PERF_CATALOG_IDS.burstBase.burstThreadId}`)
|
||||
.click();
|
||||
await waitForThreadRoute(harness.page, {
|
||||
threadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
messageId: PERF_CATALOG_IDS.burstBase.burstTerminalMessageId,
|
||||
});
|
||||
|
||||
await harness.resetBrowserMetrics();
|
||||
await harness.startAction("burst-completion");
|
||||
await typeIntoComposerAndSend(harness.page, "Run the dense websocket perf burst.");
|
||||
|
||||
await harness.page.waitForTimeout(900);
|
||||
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: "thread-switch-burst-nav",
|
||||
projectTitle,
|
||||
threadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
});
|
||||
await harness.page.waitForFunction(
|
||||
(messageNeedle) => document.body.textContent?.includes(messageNeedle as string) ?? false,
|
||||
"Navigation lane",
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
const navigationTimelineText = await harness.page
|
||||
.locator('[data-timeline-root="true"]')
|
||||
.textContent();
|
||||
expect(navigationTimelineText ?? "").toContain("Navigation lane");
|
||||
|
||||
await measureThreadSwitch(harness, {
|
||||
actionName: "thread-switch-burst-return",
|
||||
projectTitle,
|
||||
threadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
});
|
||||
|
||||
await harness.page.waitForFunction(
|
||||
(sentinelText) => document.body.textContent?.includes(sentinelText as string) ?? false,
|
||||
streamScenario.sentinelText,
|
||||
{ timeout: streamScenario.totalDurationMs + 15_000 },
|
||||
);
|
||||
await harness.endAction("burst-completion");
|
||||
|
||||
const browserMetrics = await harness.snapshotBrowserMetrics();
|
||||
const summary = summarizeBrowserPerfMetrics(browserMetrics, {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
burstActionName: "burst-completion",
|
||||
});
|
||||
|
||||
expect(summary.burstCompletionMs).not.toBeNull();
|
||||
expect(summary.burstCompletionMs ?? Number.POSITIVE_INFINITY).toBeLessThanOrEqual(
|
||||
thresholds.burstCompletionMs,
|
||||
);
|
||||
expect(summary.maxLongTaskMs).toBeLessThanOrEqual(thresholds.maxLongTaskMs);
|
||||
expect(summary.longTasksOver50Ms).toBeLessThanOrEqual(thresholds.longTasksOver50MsMax);
|
||||
expect(summary.maxRafGapMs).toBeLessThanOrEqual(thresholds.maxRafGapMs);
|
||||
|
||||
const burstNavActions = browserMetrics.actions.filter((action) =>
|
||||
action.name.startsWith("thread-switch-burst"),
|
||||
);
|
||||
expect(burstNavActions).toHaveLength(2);
|
||||
for (const action of burstNavActions) {
|
||||
expect(action.durationMs).toBeLessThanOrEqual(thresholds.threadSwitchP95Ms);
|
||||
}
|
||||
|
||||
await harness.finishRun({
|
||||
suite: "websocket-application",
|
||||
scenarioId: "dense_assistant_stream",
|
||||
thresholds,
|
||||
metadata: {
|
||||
burstSeedThreadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
navigationThreadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
fillerThreadId: PERF_CATALOG_IDS.burstBase.fillerThreadId,
|
||||
navigationLiveAssistantMessageId:
|
||||
PERF_CATALOG_IDS.provider.navigationLiveAssistantMessageId,
|
||||
burstLiveAssistantMessageId: PERF_CATALOG_IDS.provider.burstLiveAssistantMessageId,
|
||||
sentinelText: streamScenario.sentinelText,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
burstActionName: "burst-completion",
|
||||
},
|
||||
});
|
||||
finished = true;
|
||||
} finally {
|
||||
if (harness && !finished) {
|
||||
await harness.finishRun({
|
||||
suite: "websocket-application",
|
||||
scenarioId: "dense_assistant_stream",
|
||||
thresholds,
|
||||
metadata: {
|
||||
burstSeedThreadId: PERF_CATALOG_IDS.burstBase.burstThreadId,
|
||||
navigationThreadId: PERF_CATALOG_IDS.burstBase.navigationThreadId,
|
||||
fillerThreadId: PERF_CATALOG_IDS.burstBase.fillerThreadId,
|
||||
navigationLiveAssistantMessageId:
|
||||
PERF_CATALOG_IDS.provider.navigationLiveAssistantMessageId,
|
||||
burstLiveAssistantMessageId: PERF_CATALOG_IDS.provider.burstLiveAssistantMessageId,
|
||||
sentinelText: PERF_PROVIDER_SCENARIOS.dense_assistant_stream.sentinelText,
|
||||
},
|
||||
actionSummary: {
|
||||
threadSwitchActionPrefix: "thread-switch",
|
||||
burstActionName: "burst-completion",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
+10
-1
@@ -21,5 +21,14 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"include": ["src", "vite.config.ts", "test"]
|
||||
"include": [
|
||||
"src",
|
||||
"vite.config.ts",
|
||||
"test",
|
||||
"../../packages/shared/src/perf/artifact.ts",
|
||||
"../../test/perf/support/artifact.ts",
|
||||
"../../test/perf/support/browserMetrics.ts",
|
||||
"../../test/perf/support/serverSampler.ts",
|
||||
"../../test/perf/support/thresholds.ts"
|
||||
]
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import tailwindcss from "@tailwindcss/vite";
|
||||
import react, { reactCompilerPreset } from "@vitejs/plugin-react";
|
||||
import babel from "@rolldown/plugin-babel";
|
||||
import { tanstackRouter } from "@tanstack/router-plugin/vite";
|
||||
import { configDefaults } from "vitest/config";
|
||||
import { defineConfig } from "vite";
|
||||
import pkg from "./package.json" with { type: "json" };
|
||||
|
||||
@@ -56,4 +57,7 @@ export default defineConfig({
|
||||
emptyOutDir: true,
|
||||
sourcemap: buildSourcemap,
|
||||
},
|
||||
test: {
|
||||
exclude: [...configDefaults.exclude, "test/perf/**/*.perf.test.ts"],
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ["test/perf/**/*.perf.test.ts"],
|
||||
environment: "node",
|
||||
fileParallelism: false,
|
||||
maxConcurrency: 1,
|
||||
testTimeout: 180_000,
|
||||
hookTimeout: 180_000,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,267 @@
|
||||
# Performance Benchmarks
|
||||
|
||||
This repository has a local performance regression harness for the built web app and built server. It is intentionally separate from the normal unit and browser test suites.
|
||||
|
||||
The benchmark is meant to answer two questions:
|
||||
|
||||
- Does large-thread rendering and thread-to-thread navigation stay snappy?
|
||||
- Does high-frequency websocket event application stay responsive under a realistic built-app flow?
|
||||
|
||||
## What it runs
|
||||
|
||||
The perf suite does not use Vite dev mode. Each run does this:
|
||||
|
||||
1. Seeds a real server base dir with deterministic fixture data using the normal event store and projection pipeline.
|
||||
2. Starts the built `t3` server from `apps/server/dist/bin.mjs`.
|
||||
3. Serves the built web bundle from `apps/server/dist/client`.
|
||||
4. Launches Chromium with Playwright.
|
||||
5. Installs an in-page collector for action timings, long tasks, `requestAnimationFrame` gaps, and mounted timeline row counts.
|
||||
6. Writes a JSON artifact plus server stdout and stderr logs under `artifacts/perf/`.
|
||||
|
||||
The current implementation is browser-focused, but the harness already reserves a server sampling hook so later server-only CPU and memory benchmarks can share the same scenarios and artifact format.
|
||||
|
||||
## Main pieces
|
||||
|
||||
- `packages/shared/src/perf/scenarioCatalog.ts`
|
||||
- Shared scenario catalog for both seeded state and live provider traffic.
|
||||
- `apps/server/integration/perf/seedPerfState.ts`
|
||||
- Creates the temporary sqlite-backed base dir using real orchestration events and projections.
|
||||
- `apps/server/src/perf/PerfProviderAdapter.ts`
|
||||
- Perf-only mock provider that emits paced runtime events over the normal provider -> websocket -> client path.
|
||||
- `apps/web/test/perf/appHarness.ts`
|
||||
- Starts the built app, launches Chromium, installs the browser collector, and writes artifacts.
|
||||
- `test/perf/support/browserMetrics.ts`
|
||||
- Collects action durations, long tasks, `requestAnimationFrame` gaps, and mounted row samples inside the page.
|
||||
- `test/perf/support/artifact.ts`
|
||||
- Defines the JSON artifact format and summary math.
|
||||
- `test/perf/support/thresholds.ts`
|
||||
- Local budgets that currently gate the suite.
|
||||
- `test/perf/support/serverSampler.ts`
|
||||
- Extension point for future CPU and memory sampling. The current implementation is `NoopServerSampler`, so `serverMetrics` is `null` today.
|
||||
|
||||
## Scenarios
|
||||
|
||||
### `large_threads`
|
||||
|
||||
Seeded app state used by the virtualization benchmark.
|
||||
|
||||
- 5 projects
|
||||
- 30 threads total
|
||||
- 2 heavy threads
|
||||
- 1 burst thread
|
||||
- 27 light filler threads spread across all projects
|
||||
|
||||
The two heavy threads currently seed:
|
||||
|
||||
- `84` and `96` turns
|
||||
- `2,000` messages
|
||||
- periodic worklog/activity rows
|
||||
- periodic proposed-plan rows
|
||||
- frequent checkpoint rows with larger changed-file trees
|
||||
|
||||
This keeps the thread count and project list closer to a real workspace mix: many projects, many sidebar rows, and heavy conversations that stay under `100` turns while still retaining thousands of messages because each turn fans out into multiple assistant messages. The heavy timelines also include the non-message rows that tend to stress grouping, virtualization, and diff-tree rendering.
|
||||
|
||||
### `burst_base`
|
||||
|
||||
Seeded app state used by the websocket benchmark.
|
||||
|
||||
- 1 burst target thread
|
||||
- 1 navigation thread
|
||||
- 1 filler thread
|
||||
|
||||
This smaller seed keeps the focus on live websocket application while still covering cross-thread background activity.
|
||||
|
||||
### `dense_assistant_stream`
|
||||
|
||||
Live provider scenario used by the websocket benchmark.
|
||||
|
||||
- runs for about `10` seconds
|
||||
- spans `24` cycles
|
||||
- updates `3` lanes at once: `burst`, `navigation`, and `filler`
|
||||
- interleaves assistant messages with multiple worklog/tool lifecycles
|
||||
|
||||
Each cycle emits, per lane:
|
||||
|
||||
1. an assistant intro message
|
||||
2. three worklog/tool command lifecycles with file payloads
|
||||
3. an assistant followup message
|
||||
|
||||
The message fragments vary in length on purpose so the live stream does not render as uniformly sized chunks.
|
||||
|
||||
## What each benchmark asserts
|
||||
|
||||
### Virtualization benchmark
|
||||
|
||||
File: `apps/web/test/perf/virtualization.perf.test.ts`
|
||||
|
||||
This benchmark:
|
||||
|
||||
- opens the large-thread seed on the built app
|
||||
- navigates between the two heavy threads through the real sidebar
|
||||
- measures a warmup switch and then six measured thread switches
|
||||
- samples mounted timeline row counts
|
||||
- scrolls bottom -> top -> bottom to catch jank
|
||||
|
||||
It currently fails if the local budgets in `test/perf/support/thresholds.ts` are exceeded:
|
||||
|
||||
- max mounted timeline rows: `140`
|
||||
- thread switch p50: `250ms`
|
||||
- thread switch p95: `500ms`
|
||||
- max long task: `120ms`
|
||||
- max `requestAnimationFrame` gap: `120ms`
|
||||
|
||||
### Websocket benchmark
|
||||
|
||||
File: `apps/web/test/perf/websocket-application.perf.test.ts`
|
||||
|
||||
This benchmark:
|
||||
|
||||
- starts the built app with the perf provider enabled
|
||||
- opens the burst thread
|
||||
- sends one real composer message
|
||||
- lets the mock provider emit the live multi-thread websocket burst
|
||||
- switches to another thread during the burst and back again
|
||||
- waits for the sentinel text that marks the end of the scenario
|
||||
|
||||
It currently fails if these budgets are exceeded:
|
||||
|
||||
- burst completion: `14,000ms`
|
||||
- max long task: `120ms`
|
||||
- long tasks over `50ms`: `2`
|
||||
- max `requestAnimationFrame` gap: `120ms`
|
||||
- burst-time thread switches: `500ms` max each
|
||||
|
||||
## Commands
|
||||
|
||||
### One-time browser setup
|
||||
|
||||
Install Chromium for the perf suite:
|
||||
|
||||
```bash
|
||||
cd apps/web
|
||||
bun run test:perf:install
|
||||
```
|
||||
|
||||
### Run the full automated benchmark suite
|
||||
|
||||
From the repo root:
|
||||
|
||||
```bash
|
||||
bun run test:perf:web
|
||||
```
|
||||
|
||||
That command builds `@t3tools/web`, builds `t3`, and then runs the dedicated perf Vitest config.
|
||||
|
||||
### Re-run the perf suite without rebuilding
|
||||
|
||||
If the built artifacts already exist and you have not changed the built app since the last build:
|
||||
|
||||
```bash
|
||||
cd apps/web
|
||||
bun run test:perf
|
||||
```
|
||||
|
||||
### Watch the automated run in a live browser
|
||||
|
||||
```bash
|
||||
T3CODE_PERF_HEADFUL=1 bun run test:perf:web
|
||||
```
|
||||
|
||||
If you already have fresh build artifacts:
|
||||
|
||||
```bash
|
||||
cd apps/web
|
||||
T3CODE_PERF_HEADFUL=1 bun run test:perf
|
||||
```
|
||||
|
||||
### Open the seeded app manually for exploration
|
||||
|
||||
Large-thread virtualization state:
|
||||
|
||||
```bash
|
||||
bun run perf:open:build -- --scenario large_threads --open
|
||||
```
|
||||
|
||||
Websocket burst state:
|
||||
|
||||
```bash
|
||||
bun run perf:open:build -- --scenario burst_base --provider dense_assistant_stream --open
|
||||
```
|
||||
|
||||
If the app is already built, use the faster commands:
|
||||
|
||||
```bash
|
||||
bun run perf:open -- --scenario large_threads --open
|
||||
bun run perf:open -- --scenario burst_base --provider dense_assistant_stream --open
|
||||
```
|
||||
|
||||
For the websocket scenario, open the burst thread and send one message to start the live stream.
|
||||
|
||||
### Inspect the seeded topology directly
|
||||
|
||||
The seed script prints the generated project and thread summaries as JSON:
|
||||
|
||||
```bash
|
||||
bun run apps/server/scripts/seedPerfState.ts large_threads
|
||||
bun run apps/server/scripts/seedPerfState.ts burst_base
|
||||
```
|
||||
|
||||
## Artifacts
|
||||
|
||||
By default each run writes to:
|
||||
|
||||
```text
|
||||
artifacts/perf/<suite>-<scenario>-<timestamp>/
|
||||
```
|
||||
|
||||
Each run currently includes:
|
||||
|
||||
- `<suite>-<scenario>.json`
|
||||
- `<suite>-<scenario>.server.stdout.log`
|
||||
- `<suite>-<scenario>.server.stderr.log`
|
||||
|
||||
The JSON artifact contains:
|
||||
|
||||
- run metadata
|
||||
- threshold profile
|
||||
- summary metrics
|
||||
- raw browser metrics
|
||||
- `serverMetrics`, reserved for later server sampling
|
||||
|
||||
Current summary fields:
|
||||
|
||||
- `maxMountedTimelineRows`
|
||||
- `threadSwitchP50Ms`
|
||||
- `threadSwitchP95Ms`
|
||||
- `maxLongTaskMs`
|
||||
- `longTasksOver50Ms`
|
||||
- `maxRafGapMs`
|
||||
- `burstCompletionMs`
|
||||
|
||||
To change the artifact output directory for one run:
|
||||
|
||||
```bash
|
||||
T3CODE_PERF_ARTIFACT_DIR=/tmp/t3-perf bun run test:perf:web
|
||||
```
|
||||
|
||||
## Internal env vars
|
||||
|
||||
These are the perf-specific env vars in the current harness:
|
||||
|
||||
- `T3CODE_PERF_HEADFUL=1`
|
||||
- Launch Chromium headed instead of headless.
|
||||
- `T3CODE_PERF_ARTIFACT_DIR=/path/to/output`
|
||||
- Override the artifact directory.
|
||||
- `T3CODE_PERF_PROVIDER=1`
|
||||
- Enables the perf provider path on the server.
|
||||
- `T3CODE_PERF_SCENARIO=dense_assistant_stream`
|
||||
- Selects the live perf provider scenario.
|
||||
|
||||
In normal usage, the automated harness and `perf:open` script set the provider env vars for you.
|
||||
|
||||
## Notes and limitations
|
||||
|
||||
- This is a local benchmark suite. It is not wired into CI yet.
|
||||
- The normal `apps/web` test suite excludes `test/perf/**/*.perf.test.ts`. Perf tests only run through `apps/web/vitest.perf.config.ts`.
|
||||
- The budgets are intentionally conservative first-pass tripwires, not tuned production SLOs.
|
||||
- The current harness measures browser responsiveness only. Server sampling is an explicit extension point, not implemented metrics yet.
|
||||
@@ -39,6 +39,10 @@
|
||||
"typecheck": "turbo run typecheck",
|
||||
"lint": "oxlint --report-unused-disable-directives",
|
||||
"test": "turbo run test",
|
||||
"test:perf:server": "cd apps/server && bun run test:perf",
|
||||
"test:perf:web": "turbo run build --filter=@t3tools/web && turbo run build --filter=t3 && cd apps/web && bun run test:perf",
|
||||
"perf:open": "node scripts/open-perf-app.ts",
|
||||
"perf:open:build": "turbo run build --filter=@t3tools/web && turbo run build --filter=t3 && node scripts/open-perf-app.ts",
|
||||
"test:desktop-smoke": "turbo run smoke-test --filter=@t3tools/desktop",
|
||||
"fmt": "oxfmt",
|
||||
"fmt:check": "oxfmt --check",
|
||||
|
||||
@@ -3,6 +3,7 @@ import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
export const EDITORS = [
|
||||
{ id: "cursor", label: "Cursor", command: "cursor", supportsGoto: true },
|
||||
{ id: "trae", label: "Trae", command: "trae", supportsGoto: true },
|
||||
{ id: "vscode", label: "VS Code", command: "code", supportsGoto: true },
|
||||
{
|
||||
id: "vscode-insiders",
|
||||
|
||||
@@ -43,6 +43,14 @@
|
||||
"./String": {
|
||||
"types": "./src/String.ts",
|
||||
"import": "./src/String.ts"
|
||||
},
|
||||
"./perf/scenarioCatalog": {
|
||||
"types": "./src/perf/scenarioCatalog.ts",
|
||||
"import": "./src/perf/scenarioCatalog.ts"
|
||||
},
|
||||
"./perf/artifact": {
|
||||
"types": "./src/perf/artifact.ts",
|
||||
"import": "./src/perf/artifact.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
|
||||
export interface PerfLatencySample {
|
||||
readonly name: string;
|
||||
readonly durationMs: number;
|
||||
readonly startedAt: string;
|
||||
readonly endedAt: string;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface PerfLatencySummary {
|
||||
readonly count: number;
|
||||
readonly minMs: number | null;
|
||||
readonly avgMs: number | null;
|
||||
readonly p50Ms: number | null;
|
||||
readonly p95Ms: number | null;
|
||||
readonly maxMs: number | null;
|
||||
}
|
||||
|
||||
export function percentile(values: ReadonlyArray<number>, target: number): number | null {
|
||||
if (values.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const sorted = values.toSorted((left, right) => left - right);
|
||||
const clampedTarget = Math.min(Math.max(target, 0), 1);
|
||||
const index = Math.min(
|
||||
sorted.length - 1,
|
||||
Math.max(0, Math.ceil(sorted.length * clampedTarget) - 1),
|
||||
);
|
||||
return sorted[index] ?? null;
|
||||
}
|
||||
|
||||
export function summarizeLatencyValues(values: ReadonlyArray<number>): PerfLatencySummary {
|
||||
if (values.length === 0) {
|
||||
return {
|
||||
count: 0,
|
||||
minMs: null,
|
||||
avgMs: null,
|
||||
p50Ms: null,
|
||||
p95Ms: null,
|
||||
maxMs: null,
|
||||
};
|
||||
}
|
||||
|
||||
const minMs = values.reduce((currentMin, value) => Math.min(currentMin, value), values[0]!);
|
||||
const maxMs = values.reduce((currentMax, value) => Math.max(currentMax, value), values[0]!);
|
||||
const avgMs = values.reduce((sum, value) => sum + value, 0) / values.length;
|
||||
|
||||
return {
|
||||
count: values.length,
|
||||
minMs,
|
||||
avgMs,
|
||||
p50Ms: percentile(values, 0.5),
|
||||
p95Ms: percentile(values, 0.95),
|
||||
maxMs,
|
||||
};
|
||||
}
|
||||
|
||||
export function summarizeLatencySamples(
|
||||
samples: ReadonlyArray<PerfLatencySample>,
|
||||
): PerfLatencySummary {
|
||||
return summarizeLatencyValues(samples.map((sample) => sample.durationMs));
|
||||
}
|
||||
|
||||
export async function writeJsonArtifact<TArtifact extends object>(
|
||||
outputPath: string,
|
||||
artifact: TArtifact,
|
||||
): Promise<void> {
|
||||
const resolvedOutputPath = resolve(outputPath);
|
||||
await mkdir(dirname(resolvedOutputPath), { recursive: true });
|
||||
await writeFile(`${resolvedOutputPath}`, `${JSON.stringify(artifact, null, 2)}\n`, "utf8");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,402 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { once } from "node:events";
|
||||
import { access, rm } from "node:fs/promises";
|
||||
import { createServer } from "node:net";
|
||||
import { resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const repoRoot = fileURLToPath(new URL("../", import.meta.url));
|
||||
const serverBinPath = resolve(repoRoot, "apps/server/dist/bin.mjs");
|
||||
const serverClientIndexPath = resolve(repoRoot, "apps/server/dist/client/index.html");
|
||||
const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
|
||||
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
|
||||
const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__";
|
||||
const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__";
|
||||
|
||||
type PerfSeedScenarioId = "large_threads" | "burst_base";
|
||||
type PerfProviderScenarioId = "dense_assistant_stream";
|
||||
|
||||
interface PerfSeedThreadSummary {
|
||||
readonly id: string;
|
||||
readonly projectId: string;
|
||||
readonly projectTitle: string | null;
|
||||
readonly title: string;
|
||||
readonly turnCount: number | null;
|
||||
readonly messageCount: number;
|
||||
readonly activityCount: number;
|
||||
readonly proposedPlanCount: number;
|
||||
readonly checkpointCount: number;
|
||||
}
|
||||
|
||||
interface PerfSeedProjectSummary {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly workspaceRoot: string;
|
||||
readonly threadCount: number;
|
||||
}
|
||||
|
||||
interface PerfSeededState {
|
||||
readonly scenarioId: PerfSeedScenarioId;
|
||||
readonly runParentDir: string;
|
||||
readonly baseDir: string;
|
||||
readonly workspaceRoot: string;
|
||||
readonly projectTitle: string | null;
|
||||
readonly projectSummaries: ReadonlyArray<PerfSeedProjectSummary>;
|
||||
readonly threadSummaries: ReadonlyArray<PerfSeedThreadSummary>;
|
||||
}
|
||||
|
||||
interface CliOptions {
|
||||
readonly scenarioId: PerfSeedScenarioId;
|
||||
readonly providerScenarioId: PerfProviderScenarioId | null;
|
||||
readonly host: string;
|
||||
readonly port: number;
|
||||
readonly openBrowser: boolean;
|
||||
}
|
||||
|
||||
function printHelp(): void {
|
||||
process.stdout.write(
|
||||
[
|
||||
"Usage: bun run perf:open -- [options]",
|
||||
"",
|
||||
"Options:",
|
||||
" --scenario <large_threads|burst_base> Seed scenario to launch (default: large_threads)",
|
||||
" --provider <dense_assistant_stream> Enable perf provider burst mode",
|
||||
" --host <host> Host to bind (default: 127.0.0.1)",
|
||||
" --port <port> Port to bind (default: random free port)",
|
||||
" --open Open the URL in your default browser",
|
||||
" --help Show this help",
|
||||
"",
|
||||
"Examples:",
|
||||
" bun run perf:open -- --scenario large_threads --open",
|
||||
" bun run perf:open -- --scenario burst_base --provider dense_assistant_stream --open",
|
||||
"",
|
||||
"Notes:",
|
||||
" - This launches the built app, not Vite dev mode.",
|
||||
" - Build artifacts must already exist. Run `bun run test:perf:web` once, or build `@t3tools/web` and `t3` manually.",
|
||||
" - With `--provider dense_assistant_stream`, open the burst thread and send one message to trigger the live multi-thread websocket burst.",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
}
|
||||
|
||||
function parseArgs(argv: ReadonlyArray<string>): CliOptions {
|
||||
let scenarioId: PerfSeedScenarioId = "large_threads";
|
||||
let providerScenarioId: PerfProviderScenarioId | null = null;
|
||||
let host = "127.0.0.1";
|
||||
let port = 0;
|
||||
let openBrowser = false;
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const argument = argv[index];
|
||||
switch (argument) {
|
||||
case "--scenario": {
|
||||
const next = argv[index + 1];
|
||||
if (next !== "large_threads" && next !== "burst_base") {
|
||||
throw new Error(
|
||||
`Expected a valid perf seed scenario after --scenario, received '${next ?? "<missing>"}'.`,
|
||||
);
|
||||
}
|
||||
scenarioId = next;
|
||||
index += 1;
|
||||
break;
|
||||
}
|
||||
case "--provider": {
|
||||
const next = argv[index + 1];
|
||||
if (next !== "dense_assistant_stream") {
|
||||
throw new Error(
|
||||
`Expected a valid perf provider scenario after --provider, received '${next ?? "<missing>"}'.`,
|
||||
);
|
||||
}
|
||||
providerScenarioId = next;
|
||||
index += 1;
|
||||
break;
|
||||
}
|
||||
case "--host": {
|
||||
const next = argv[index + 1];
|
||||
if (!next) {
|
||||
throw new Error("Expected a host value after --host.");
|
||||
}
|
||||
host = next;
|
||||
index += 1;
|
||||
break;
|
||||
}
|
||||
case "--port": {
|
||||
const next = argv[index + 1];
|
||||
const parsed = next ? Number.parseInt(next, 10) : Number.NaN;
|
||||
if (!Number.isInteger(parsed) || parsed < 0 || parsed > 65535) {
|
||||
throw new Error(`Expected a valid port after --port, received '${next ?? "<missing>"}'.`);
|
||||
}
|
||||
port = parsed;
|
||||
index += 1;
|
||||
break;
|
||||
}
|
||||
case "--open":
|
||||
openBrowser = true;
|
||||
break;
|
||||
case "--help":
|
||||
case "-h":
|
||||
printHelp();
|
||||
process.exit(0);
|
||||
default:
|
||||
throw new Error(`Unknown argument '${argument}'. Use --help for usage.`);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
scenarioId,
|
||||
providerScenarioId,
|
||||
host,
|
||||
port,
|
||||
openBrowser,
|
||||
};
|
||||
}
|
||||
|
||||
async function pickFreePort(): Promise<number> {
|
||||
return await new Promise<number>((resolvePort, reject) => {
|
||||
const server = createServer();
|
||||
server.on("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") {
|
||||
reject(new Error("Unable to resolve a free localhost port."));
|
||||
return;
|
||||
}
|
||||
server.close((closeError) => {
|
||||
if (closeError) {
|
||||
reject(closeError);
|
||||
return;
|
||||
}
|
||||
resolvePort(address.port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function verifyBuiltArtifacts(): Promise<void> {
|
||||
await Promise.all([access(serverBinPath), access(serverClientIndexPath)]).catch(() => {
|
||||
throw new Error(
|
||||
`Built perf artifacts are missing. Expected ${serverBinPath} and ${serverClientIndexPath}. Run bun run test:perf:web or build the app first.`,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function parsePerfSeededState(stdout: string): PerfSeededState {
|
||||
const startIndex = stdout.lastIndexOf(PERF_SEED_JSON_START);
|
||||
const endIndex = stdout.lastIndexOf(PERF_SEED_JSON_END);
|
||||
|
||||
if (startIndex === -1 || endIndex === -1 || endIndex <= startIndex) {
|
||||
throw new Error(`Perf seed command did not emit the expected JSON markers.\n${stdout}`);
|
||||
}
|
||||
|
||||
const payload = stdout.slice(startIndex + PERF_SEED_JSON_START.length, endIndex).trim();
|
||||
return JSON.parse(payload) as PerfSeededState;
|
||||
}
|
||||
|
||||
async function seedPerfState(scenarioId: PerfSeedScenarioId): Promise<PerfSeededState> {
|
||||
const seedProcess = spawn("bun", ["run", "apps/server/scripts/seedPerfState.ts", scenarioId], {
|
||||
cwd: repoRoot,
|
||||
env: process.env,
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
seedProcess.stdout?.on("data", (chunk) => {
|
||||
stdout += chunk.toString();
|
||||
});
|
||||
seedProcess.stderr?.on("data", (chunk) => {
|
||||
stderr += chunk.toString();
|
||||
});
|
||||
|
||||
const [exitCode] = (await once(seedProcess, "exit")) as [number | null];
|
||||
if (exitCode !== 0) {
|
||||
throw new Error(`Perf seed command failed with code ${exitCode ?? "unknown"}.\n${stderr}`);
|
||||
}
|
||||
|
||||
return parsePerfSeededState(stdout);
|
||||
}
|
||||
|
||||
async function waitForServerReady(url: string, process: ChildProcess): Promise<void> {
|
||||
const startedAt = Date.now();
|
||||
const timeoutMs = 45_000;
|
||||
const requestTimeoutMs = 1_000;
|
||||
|
||||
while (Date.now() - startedAt < timeoutMs) {
|
||||
if (process.exitCode !== null) {
|
||||
throw new Error(`Perf server exited early with code ${process.exitCode}.`);
|
||||
}
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
redirect: "manual",
|
||||
signal: AbortSignal.timeout(requestTimeoutMs),
|
||||
});
|
||||
if (response.ok) {
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Ignore connection races during startup.
|
||||
}
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 200));
|
||||
}
|
||||
|
||||
throw new Error(`Timed out waiting for perf server readiness at ${url}.`);
|
||||
}
|
||||
|
||||
async function stopChildProcess(process: ChildProcess): Promise<void> {
|
||||
if (process.exitCode !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.kill("SIGTERM");
|
||||
const exited = await new Promise<boolean>((resolveExited) => {
|
||||
const timer = setTimeout(() => resolveExited(false), 5_000);
|
||||
process.once("exit", () => {
|
||||
clearTimeout(timer);
|
||||
resolveExited(true);
|
||||
});
|
||||
});
|
||||
|
||||
if (!exited && process.exitCode === null) {
|
||||
process.kill("SIGKILL");
|
||||
await new Promise<void>((resolveExited) => {
|
||||
process.once("exit", () => resolveExited());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function cleanupPerfRunDir(runParentDir: string): Promise<void> {
|
||||
await rm(runParentDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
function openUrl(url: string): void {
|
||||
const command: [string, ...string[]] =
|
||||
process.platform === "darwin"
|
||||
? ["open", url]
|
||||
: process.platform === "win32"
|
||||
? ["cmd", "/c", "start", "", url]
|
||||
: ["xdg-open", url];
|
||||
const child = spawn(command[0], command.slice(1), {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
child.unref();
|
||||
}
|
||||
|
||||
function printSeedSummary(
|
||||
seededState: PerfSeededState,
|
||||
url: string,
|
||||
providerScenarioId: string | null,
|
||||
): void {
|
||||
process.stdout.write(`\nPerf app ready at ${url}\n`);
|
||||
process.stdout.write(`Scenario: ${seededState.scenarioId}\n`);
|
||||
process.stdout.write(`Base dir: ${seededState.baseDir}\n`);
|
||||
process.stdout.write(`Primary workspace: ${seededState.workspaceRoot}\n`);
|
||||
process.stdout.write("Projects:\n");
|
||||
for (const project of seededState.projectSummaries) {
|
||||
process.stdout.write(
|
||||
` - ${project.title} (${project.id}): ${project.threadCount} threads, ${project.workspaceRoot}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
process.stdout.write("Threads:\n");
|
||||
for (const thread of seededState.threadSummaries.toSorted(
|
||||
(left, right) =>
|
||||
right.messageCount - left.messageCount || left.title.localeCompare(right.title),
|
||||
)) {
|
||||
process.stdout.write(
|
||||
` - ${thread.projectTitle ?? "<unknown project>"} / ${thread.title} (${thread.id}): ${thread.turnCount ?? "?"} turns, ${thread.messageCount} messages, ${thread.activityCount} worklog rows, ${thread.proposedPlanCount} plans, ${thread.checkpointCount} checkpoints\n`,
|
||||
);
|
||||
}
|
||||
|
||||
if (providerScenarioId !== null) {
|
||||
process.stdout.write("\nLive burst mode is enabled.\n");
|
||||
process.stdout.write(
|
||||
"Open the burst thread and send one message to trigger the multi-thread websocket burst.\n",
|
||||
);
|
||||
}
|
||||
|
||||
process.stdout.write("\nPress Ctrl+C to stop the server.\n\n");
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
await verifyBuiltArtifacts();
|
||||
const seededState = await seedPerfState(options.scenarioId);
|
||||
const port = options.port === 0 ? await pickFreePort() : options.port;
|
||||
|
||||
const serverProcess = spawn(
|
||||
"node",
|
||||
[
|
||||
serverBinPath,
|
||||
"--mode",
|
||||
"web",
|
||||
"--host",
|
||||
options.host,
|
||||
"--port",
|
||||
port.toString(),
|
||||
"--base-dir",
|
||||
seededState.baseDir,
|
||||
"--no-browser",
|
||||
],
|
||||
{
|
||||
cwd: repoRoot,
|
||||
env: {
|
||||
...process.env,
|
||||
...(options.providerScenarioId
|
||||
? {
|
||||
[PERF_PROVIDER_ENV]: "1",
|
||||
[PERF_SCENARIO_ENV]: options.providerScenarioId,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
stdio: ["ignore", "inherit", "inherit"],
|
||||
},
|
||||
);
|
||||
|
||||
let shuttingDown = false;
|
||||
const shutdown = async (signal: NodeJS.Signals) => {
|
||||
if (shuttingDown) {
|
||||
return;
|
||||
}
|
||||
shuttingDown = true;
|
||||
process.stdout.write(`\nReceived ${signal}. Stopping perf app...\n`);
|
||||
await stopChildProcess(serverProcess);
|
||||
await cleanupPerfRunDir(seededState.runParentDir);
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
process.on("SIGINT", () => {
|
||||
void shutdown("SIGINT");
|
||||
});
|
||||
process.on("SIGTERM", () => {
|
||||
void shutdown("SIGTERM");
|
||||
});
|
||||
|
||||
try {
|
||||
const url = `http://${options.host}:${port.toString()}`;
|
||||
await waitForServerReady(url, serverProcess);
|
||||
printSeedSummary(seededState, url, options.providerScenarioId);
|
||||
|
||||
if (options.openBrowser) {
|
||||
openUrl(url);
|
||||
}
|
||||
|
||||
const [exitCode] = (await once(serverProcess, "exit")) as [number | null];
|
||||
if (!shuttingDown) {
|
||||
await cleanupPerfRunDir(seededState.runParentDir);
|
||||
process.exit(exitCode ?? 0);
|
||||
}
|
||||
} catch (error) {
|
||||
await stopChildProcess(serverProcess);
|
||||
await cleanupPerfRunDir(seededState.runParentDir);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await main();
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
process.stderr.write(`${message}\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import {
|
||||
percentile,
|
||||
summarizeLatencySamples,
|
||||
summarizeLatencyValues,
|
||||
type PerfLatencySample,
|
||||
type PerfLatencySummary,
|
||||
writeJsonArtifact,
|
||||
} from "../../../packages/shared/src/perf/artifact";
|
||||
import type { PerfThresholdProfile } from "./thresholds.ts";
|
||||
|
||||
export interface PerfActionDuration {
|
||||
readonly name: string;
|
||||
readonly durationMs: number;
|
||||
readonly startedAtMs: number;
|
||||
readonly endedAtMs: number;
|
||||
}
|
||||
|
||||
export interface PerfLongTaskSample {
|
||||
readonly startTimeMs: number;
|
||||
readonly durationMs: number;
|
||||
readonly name: string;
|
||||
}
|
||||
|
||||
export interface PerfMountedRowSample {
|
||||
readonly label: string;
|
||||
readonly count: number;
|
||||
readonly capturedAtMs: number;
|
||||
}
|
||||
|
||||
export interface BrowserPerfMetrics {
|
||||
readonly actions: ReadonlyArray<PerfActionDuration>;
|
||||
readonly longTasks: ReadonlyArray<PerfLongTaskSample>;
|
||||
readonly rafGapsMs: ReadonlyArray<number>;
|
||||
readonly mountedRowSamples: ReadonlyArray<PerfMountedRowSample>;
|
||||
}
|
||||
|
||||
export interface PerfServerMetricSample {
|
||||
readonly capturedAt: string;
|
||||
readonly cpuUserMicros?: number;
|
||||
readonly cpuSystemMicros?: number;
|
||||
readonly rssBytes?: number;
|
||||
readonly heapTotalBytes?: number;
|
||||
readonly heapUsedBytes?: number;
|
||||
readonly externalBytes?: number;
|
||||
readonly arrayBuffersBytes?: number;
|
||||
}
|
||||
|
||||
export interface PerfArtifactSummary {
|
||||
readonly maxMountedTimelineRows: number;
|
||||
readonly threadSwitchP50Ms: number | null;
|
||||
readonly threadSwitchP95Ms: number | null;
|
||||
readonly maxLongTaskMs: number;
|
||||
readonly longTasksOver50Ms: number;
|
||||
readonly maxRafGapMs: number;
|
||||
readonly burstCompletionMs: number | null;
|
||||
}
|
||||
|
||||
export type { PerfLatencySample, PerfLatencySummary };
|
||||
export { percentile, summarizeLatencySamples, summarizeLatencyValues, writeJsonArtifact };
|
||||
|
||||
export interface PerfRunArtifact {
|
||||
readonly suite: string;
|
||||
readonly scenarioId: string;
|
||||
readonly startedAt: string;
|
||||
readonly completedAt: string;
|
||||
readonly thresholds: PerfThresholdProfile;
|
||||
readonly summary: PerfArtifactSummary;
|
||||
readonly browserMetrics: BrowserPerfMetrics;
|
||||
readonly serverMetrics: ReadonlyArray<PerfServerMetricSample> | null;
|
||||
readonly metadata?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export function summarizeBrowserPerfMetrics(
|
||||
browserMetrics: BrowserPerfMetrics,
|
||||
options?: {
|
||||
readonly threadSwitchActionPrefix?: string;
|
||||
readonly burstActionName?: string;
|
||||
},
|
||||
): PerfArtifactSummary {
|
||||
const threadSwitchActions = browserMetrics.actions
|
||||
.filter((action) =>
|
||||
options?.threadSwitchActionPrefix
|
||||
? action.name.startsWith(options.threadSwitchActionPrefix)
|
||||
: action.name.startsWith("thread-switch"),
|
||||
)
|
||||
.map((action) => action.durationMs);
|
||||
const burstCompletionAction = browserMetrics.actions.find(
|
||||
(action) => action.name === (options?.burstActionName ?? "burst-completion"),
|
||||
);
|
||||
const maxMountedTimelineRows = browserMetrics.mountedRowSamples.reduce(
|
||||
(maxCount, sample) => Math.max(maxCount, sample.count),
|
||||
0,
|
||||
);
|
||||
const maxLongTaskMs = browserMetrics.longTasks.reduce(
|
||||
(maxDuration, sample) => Math.max(maxDuration, sample.durationMs),
|
||||
0,
|
||||
);
|
||||
const longTasksOver50Ms = browserMetrics.longTasks.filter(
|
||||
(sample) => sample.durationMs > 50,
|
||||
).length;
|
||||
const maxRafGapMs = browserMetrics.rafGapsMs.reduce((maxGap, gap) => Math.max(maxGap, gap), 0);
|
||||
|
||||
return {
|
||||
maxMountedTimelineRows,
|
||||
threadSwitchP50Ms: percentile(threadSwitchActions, 0.5),
|
||||
threadSwitchP95Ms: percentile(threadSwitchActions, 0.95),
|
||||
maxLongTaskMs,
|
||||
longTasksOver50Ms,
|
||||
maxRafGapMs,
|
||||
burstCompletionMs: burstCompletionAction?.durationMs ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function writePerfArtifact(
|
||||
outputPath: string,
|
||||
artifact: PerfRunArtifact,
|
||||
): Promise<void> {
|
||||
await writeJsonArtifact(outputPath, artifact);
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import type { BrowserPerfMetrics } from "./artifact.ts";
|
||||
|
||||
export const PERF_BROWSER_GLOBAL = "__t3PerfCollector";
|
||||
const DEFAULT_TIMELINE_ROW_SELECTOR = "[data-timeline-row-kind]";
|
||||
|
||||
export interface BrowserPerfCollector {
|
||||
readonly startAction: (name: string) => void;
|
||||
readonly endAction: (name: string) => number | null;
|
||||
readonly sampleMountedRows: (label: string) => number;
|
||||
readonly snapshot: () => BrowserPerfMetrics;
|
||||
readonly reset: () => void;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__t3PerfCollector?: BrowserPerfCollector;
|
||||
}
|
||||
}
|
||||
|
||||
export function installBrowserPerfCollector(
|
||||
timelineRowSelector = DEFAULT_TIMELINE_ROW_SELECTOR,
|
||||
): void {
|
||||
if (typeof window === "undefined" || window.__t3PerfCollector) {
|
||||
return;
|
||||
}
|
||||
|
||||
const actionStarts = new Map<string, number>();
|
||||
const actions: Array<BrowserPerfMetrics["actions"][number]> = [];
|
||||
const longTasks: Array<BrowserPerfMetrics["longTasks"][number]> = [];
|
||||
const rafGapsMs: number[] = [];
|
||||
const mountedRowSamples: Array<BrowserPerfMetrics["mountedRowSamples"][number]> = [];
|
||||
let previousAnimationFrameTs = 0;
|
||||
let rafHandle = 0;
|
||||
|
||||
const animationFrameLoop = (timestampMs: number) => {
|
||||
if (previousAnimationFrameTs > 0) {
|
||||
rafGapsMs.push(timestampMs - previousAnimationFrameTs);
|
||||
}
|
||||
previousAnimationFrameTs = timestampMs;
|
||||
rafHandle = window.requestAnimationFrame(animationFrameLoop);
|
||||
};
|
||||
rafHandle = window.requestAnimationFrame(animationFrameLoop);
|
||||
|
||||
if (typeof PerformanceObserver !== "undefined") {
|
||||
try {
|
||||
const longTaskObserver = new PerformanceObserver((list: PerformanceObserverEntryList) => {
|
||||
for (const entry of list.getEntries()) {
|
||||
longTasks.push({
|
||||
name: entry.name,
|
||||
startTimeMs: entry.startTime,
|
||||
durationMs: entry.duration,
|
||||
});
|
||||
}
|
||||
});
|
||||
longTaskObserver.observe({ entryTypes: ["longtask"] } as PerformanceObserverInit);
|
||||
} catch {
|
||||
// Ignore browsers or runtimes that do not expose long-task observation.
|
||||
}
|
||||
}
|
||||
|
||||
const readMountedRows = () => document.querySelectorAll(timelineRowSelector).length;
|
||||
|
||||
window.__t3PerfCollector = {
|
||||
startAction(name: string) {
|
||||
actionStarts.set(name, performance.now());
|
||||
},
|
||||
endAction(name: string) {
|
||||
const startedAtMs = actionStarts.get(name);
|
||||
if (startedAtMs === undefined) {
|
||||
return null;
|
||||
}
|
||||
const endedAtMs = performance.now();
|
||||
const durationMs = endedAtMs - startedAtMs;
|
||||
actions.push({
|
||||
name,
|
||||
durationMs,
|
||||
startedAtMs,
|
||||
endedAtMs,
|
||||
});
|
||||
actionStarts.delete(name);
|
||||
return durationMs;
|
||||
},
|
||||
sampleMountedRows(label: string) {
|
||||
const count = readMountedRows();
|
||||
mountedRowSamples.push({
|
||||
label,
|
||||
count,
|
||||
capturedAtMs: performance.now(),
|
||||
});
|
||||
return count;
|
||||
},
|
||||
snapshot() {
|
||||
return {
|
||||
actions: [...actions],
|
||||
longTasks: [...longTasks],
|
||||
rafGapsMs: [...rafGapsMs],
|
||||
mountedRowSamples: [...mountedRowSamples],
|
||||
};
|
||||
},
|
||||
reset() {
|
||||
actionStarts.clear();
|
||||
actions.length = 0;
|
||||
longTasks.length = 0;
|
||||
rafGapsMs.length = 0;
|
||||
mountedRowSamples.length = 0;
|
||||
previousAnimationFrameTs = 0;
|
||||
window.cancelAnimationFrame(rafHandle);
|
||||
rafHandle = window.requestAnimationFrame(animationFrameLoop);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "../../../packages/shared/src/perf/scenarioCatalog";
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { PerfServerMetricSample } from "./artifact.ts";
|
||||
|
||||
export interface PerfServerSampler {
|
||||
readonly start: (input: { readonly pid: number }) => Promise<void>;
|
||||
readonly stop: () => Promise<ReadonlyArray<PerfServerMetricSample> | null>;
|
||||
}
|
||||
|
||||
export class NoopServerSampler implements PerfServerSampler {
|
||||
async start(_input: { readonly pid: number }): Promise<void> {}
|
||||
|
||||
async stop(): Promise<null> {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
export interface PerfThresholdProfile {
|
||||
readonly maxMountedTimelineRows: number;
|
||||
readonly threadSwitchP50Ms: number;
|
||||
readonly threadSwitchP95Ms: number;
|
||||
readonly maxLongTaskMs: number;
|
||||
readonly maxRafGapMs: number;
|
||||
readonly burstCompletionMs: number;
|
||||
readonly longTasksOver50MsMax: number;
|
||||
}
|
||||
|
||||
export const PERF_THRESHOLDS = {
|
||||
local: {
|
||||
maxMountedTimelineRows: 140,
|
||||
threadSwitchP50Ms: 250,
|
||||
threadSwitchP95Ms: 500,
|
||||
maxLongTaskMs: 120,
|
||||
maxRafGapMs: 120,
|
||||
burstCompletionMs: 14_000,
|
||||
longTasksOver50MsMax: 2,
|
||||
},
|
||||
} as const satisfies Record<string, PerfThresholdProfile>;
|
||||
|
||||
export type PerfThresholdProfileName = keyof typeof PERF_THRESHOLDS;
|
||||
Reference in new issue
Block a user